2016-12-13 23 views
0

我在我的視圖中有一個隱藏幫助器,我想在其中傳遞子集合。我希望能夠訂購集合,然後在hiddenfor中獲得我想要的財產。Linq在htmlhelper中獲取集合中的項目

這就是我想要做的。

@Html.HiddenFor(m => m.Licenses.OrderByDescending(x => x.IssueDate).FirstOrDefault().Active) 

這只是呈現Model.Active代替Model.Licenses [指數]。主動

是否有傭工使用Linq這樣還是我需要創建一個自定義幫助的方法嗎?

回答

1

用作Html.BlarghFor()方法參數的Expression<>需要是一個簡單的表達式,就像屬性getter調用一樣,不能涉及任何方法調用。這是ASP.NET MVC中的模型綁定器的工作原理。

您的視圖模型不應該是特定於該視圖中的實體框架的實體對象,而是一個類,它應該只包含標量值,嵌套視圖模型和瑣碎的集合(數組,List<T>Dictionary<TKey,TValue>的 - 這樣做而不是在您的ViewModel中使用IQueryableIEnumerable) - 同樣,這一切都與模型綁定器的工作方式有關。

一種解決方案是通過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集合爲空的可能性也需要處理。

+0

因爲我正在使用編輯器模板,所以在控制器中設置它會很困難。 https://metalant.wordpress.com/2013/12/07/html-editorfor-and-collections/我會嘗試在視圖中排序的建議。 – forwheeler

+0

這對我有用,謝謝 – forwheeler

相關問題