用作Html.BlarghFor()
方法參數的Expression<>
需要是一個簡單的表達式,就像屬性getter調用一樣,不能涉及任何方法調用。這是ASP.NET MVC中的模型綁定器的工作原理。
您的視圖模型不應該是特定於該視圖中的實體框架的實體對象,而是一個類,它應該只包含標量值,嵌套視圖模型和瑣碎的集合(數組,List<T>
和Dictionary<TKey,TValue>
的 - 這樣做而不是在您的ViewModel中使用IQueryable
或IEnumerable
) - 同樣,這一切都與模型綁定器的工作方式有關。
一種解決方案是通過IssueDate
在您的控制器預先整理m.Licenses
:
[...]
viewModel.Licenses.Sort((x,y) => x.IssueDate.CompareTo(y.IssueDate));
return this.View(viewModel);
而在你的看法:
@Html.HiddenFor(m => m.Licenses[ m.Licenses.Count - 1 ].Active)
另一種選擇是找到你想要的元素的索引和然後在你的Expression<>
參數中使用它。
不幸的是,LINQ的不來一個「索引的-MAX /分鐘」的功能,你可以寫你自己的(從這裏開始:How do I get the index of the highest value in an array using LINQ?),或做手工:
@{
// at the start of your view:
Int32 indexOfMostRecent = -1;
DateTime mostRecent = DateTime.MinValue;
for(Int32 i = 0; i < this.Model.Licenses.Count; i++) {
if(this.Model.Licenses[i].IssueDate > mostRecent) {
indexOfMostRecent = i;
mostRecent = this.Model.Licenses[i].IssueDate;
}
}
}
@Html.HiddenFor(m => m.Licenses[ indexOfMostRecent ].Active)
如果有Licenses
集合爲空的可能性也需要處理。
來源
2016-12-13 19:27:36
Dai
因爲我正在使用編輯器模板,所以在控制器中設置它會很困難。 https://metalant.wordpress.com/2013/12/07/html-editorfor-and-collections/我會嘗試在視圖中排序的建議。 – forwheeler
這對我有用,謝謝 – forwheeler