无法访问模型的属性(vs Model)?

时间:2015-05-19 14:52:31

标签: c# asp.net-mvc-5

目前我有一个视图,它采用IEnumerable模型,我用它来显示视图上的数据。但是在同一视图中我还有一个模态弹出窗口,我想在其中添加到模型而不是将它们分成不同的视图。我试着按照这个问题How to access model property in Razor view of IEnumerable Type?底部的建议,但得到了例外

  

表达式编译器无法评估索引器表达式'(model.Count - 1)',因为它引用了不可用的模型参数'model'。

在视图的顶部我有

@model IList<Test.Models.DashModel>

在我的模态体内,我有

 @using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>DashboardModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model[model.Count - 1].DashName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model[model.Count - 1].DashName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model[model.Count - 1].DashName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model[model.Count - 1].CreatedDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model[model.Count - 1].CreatedDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model[model.Count - 1].CreatedDate, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
}

1 个答案:

答案 0 :(得分:4)

我同意过度使用 Model 这个词,即@model关键字,相同类型的Model实例变量,以及默认名称model给予HtmlHelper方法的lambda参数名称实在令人困惑。

不幸的是,model在这种情况下是Html.*For扩展方法传递给lambda的参数。 IMO脚手架视图可以为lambdas选择一个较少冲突的参数变量名称,例如: mx等。

要访问传递给视图的实际ViewModel实例(即在剃刀@model顶部定义的.cshtml,即@model IList<Test.Models.DashModel>),您要执行的操作是访问 Model (请注意案例差异):

  @Html.LabelFor(model => Model.Last().CreatedDate, ...

我还建议使用Linq扩展方法,例如Last() / First()等,而不是使用数组索引器。

出于兴趣,您当然可以将参数名称更改为您喜欢的任何内容,例如

  @Html.LabelFor(_ => Model.Last().CreatedDate, ...
相关问题