2015-05-19 89 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