2015-05-19 73 views
1

目前我有一个视图,它采用IEnumerable模型,我用它来在视图上显示数据。然而,在相同的观点,我也有一个模式弹出,我想添加到模型,而不是将它们分离到不同的意见。我试图按照在这个问题How to access model property in Razor view of IEnumerable Type?底部的建议,但有一个例外无法访问模型(vs模型)的属性?

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

在视图的顶部,我有

@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> 
} 
+0

尝试Model.Count(含上限M) – Carl

+1

既然你查看有一个表单只能编辑一个对象,那么究竟为什么你传递一个集合的观点,而不是一个对象 –

回答

4

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

不幸的是model在这种情况下是Html.*For扩展方法传入您的lambda的参数。 IMO脚手架的视图可能已经为lambda表达选择了一个不太矛盾的参数变量名称,例如, mx

访问实际ViewModel实例传递给视图(即@model在你的剃须刀.cshtml顶部定义,即@model IList<Test.Models.DashModel>),你想要做什么是访问Model(请注意大小写差):

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

我也建议使用Linq扩展方法如Last()/First()等,而不是使用阵列索引。

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

@Html.LabelFor(_ => Model.Last().CreatedDate, ... 
+0

,我会尝试这一点,给你一个勾号,如果它的工作! – Johnathon64