2009-12-15 68 views
0

我有一個循環在我的視圖代碼中創建一個表單。在表格的每個項目都有自己的下拉列表中,他們所有的份額從視圖數據:在視圖代碼中設置下拉列表中的選定項目

<%foreach(Foo i in Model){ %> 
    <tr> 
     <td><%=i.title%></td> 
     <td><%=Html.DropDownList("order"+i.id.ToString(), ViewData["SequenceDropDown"] as SelectList)%></td> 
    </tr> 
    <%} %> 

我需要它,因此選擇的項目是基於美孚(i.Sequence)的屬性。我似乎找不到辦法做到這一點?

我可以在控制器中做到這一點,但我希望能夠在所有項目中共享選擇列表並相應地選擇所選項目。

回答

1

我想你必須在你的動作中創建一個SelectItem列表的數組,它能正確識別每個實例的選定項目。然後,您可以從該陣列創建您的下拉列表。

這將是一個更清潔的實現,而不是在視圖中這樣做,因爲視圖應該儘可能愚蠢。

+0

是的,但然後視圖將不得不根據項目是什麼在視圖數據中選擇正確的項目。這對我來說會使代碼變得更加笨拙,當然也不會讓視圖變得愚蠢 – qui 2009-12-15 16:22:28

+1

當您在Action中創建SelectList時,您可以像http://msdn.microsoft.com/en-us/library/中那樣定義所選項目dd492553.aspx,所有View然後需要遍歷ViewData數組的選擇列表(與您的Model迭代器同步)並實例化下拉列表。理想情況下,您可以擴展您的Foo對象以包含SelectList對象,或者在此上下文中使用用於顯示Foo的中間對象。 – Lazarus 2009-12-15 16:42:25

+0

您當然不需要這樣做,但它絕對可以讓視圖更易於閱讀。 – 2009-12-16 05:56:30

0

我寫了一個快速流暢的擴展方法來做到這一點:

public static IEnumerable<SelectListItem> WithSelected(this IEnumerable<SelectListItem> selectListItems, object selectedvalue) 
    { 
     var newItems = new List<SelectListItem>(selectListItems); 

     foreach(var item in newItems) 
      item.Selected = item.Value == selectedvalue.ToString(); 

     return newItems; 
    } 

    public static IEnumerable<CheckBoxItem> WithSelected(this IEnumerable<CheckBoxItem> selectListItems, int selectedvalue) 
    { 
     var newItems = new List<CheckBoxItem>(selectListItems); 

     foreach (var item in newItems) 
      item.Checked = item.Id == selectedvalue; 

     return newItems; 
    } 

    public static IEnumerable<CheckBoxItem> WithSelected(this IEnumerable<CheckBoxItem> selectListItems, IEnumerable<int> selectedvalues) 
    { 
     var newItems = new List<CheckBoxItem>(selectListItems); 

     foreach (var item in newItems) 
      item.Checked = selectedvalues.Contains(item.Id); 

     return newItems; 
    } 

可以通過機我想,但它工作正常。用法如下:

<%foreach(Foo i in Model){ %> 
<tr> 
    <td><%=i.title%></td> 
    <td><%=Html.DropDownList("order"+i.id.ToString(), (ViewData["SequenceDropDown"] as SelectList)).WithSelected(i.Sequence) %></td> 
</tr> 
<%} %> 
相關問題