目前我有一个 View 采用 IEnumerable 模型,我用它在 View 上显示数据。但是,在同一个 View 中,我还有一个模式弹出窗口,我想在其中添加到模型中,而不是将它们分成不同的 View 。我试着按照这个问题底部的建议 How to access model property in Razor view of IEnumerable Type?但是有一个异常(exception)
The expression compiler was unable to evaluate the indexer expression '(model.Count - 1)' because it references the model parameter 'model' which is unavailable.
在我的 View 顶部
@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>
}
请您参考如下方法:
我同意过度使用 Model 这个词,即 @model关键字,Model相同类型的实例变量,默认名称model赋予 HtmlHelper 的 lambda 参数名称方法真的很困惑。
不幸的是model在本例中是 Html.*For 传递的参数将方法扩展到您的 lambda 中。 IMO 脚手架 View 可以为 lambda 选择冲突较少的参数变量名称,例如m或 x等
访问实际的ViewModel传递给 View 的实例(即 @model 定义在 Razor 顶部 .cshtml ,即 @model IList<Test.Models.DashModel> ),您要做的是访问 Model (注意大小写区别):
@Html.LabelFor(model => Model.Last().CreatedDate, ...
我还建议使用 Linq扩展方法,例如 Last() / First()等等,而不是使用数组索引器。
出于兴趣,您当然可以将参数名称更改为任何您喜欢的名称,例如
@Html.LabelFor(_ => Model.Last().CreatedDate, ...
