2010-06-01 56 views
5

正確的價值觀,我有我RoomType類:將我的列表<Roomtype>轉換爲ASP的SelectList。 NET MVC DropDownFor <>,並得到每個選項項目

Int32 Id 
String Name 
String ColorCode 

我的視圖模型得到應顯示在下拉列表中List<Roomtype> RoomTypes

每個下拉選項都應該有:1)作爲標題Name,2)作爲值Id,以及3)風格背景顏色#ColorCode

我的問題是如何正確地將此列表轉換爲List<SelectListItem>,按照ASP.NET MVC的DropDownFor幫助程序的要求,然後爲每個選項插入正確的值。我試圖在我的viewmodel有一個新的只讀屬性,其中有一個getter RoomtypeSelectList,它返回new SelectList(RoomTypeList),但我不能得到正確的屬性顯示(名稱,ID,背景色)。

我會很感激的方向是正確的一些幫助或指針...

回答

2

內置的HTML輔助方法不會讓你產生樣式或標題屬性的選擇列表項。

如果您想要添加這些屬性,您需要創建自己的html助手方法,或者只需使用<% foreach ... %>手動輸出選擇列表。

9

在視圖中嘗試這樣的事情

<%=Html.DropDownList("userList", new SelectList((IEnumerable)ViewData["RoomTypes"], "Value", "Text",selectedValue)) %> 
在你的控制器動作

你必須

List<SelectListItem> roomTypesSelect = new List<SelectListItem>(); 

    IList roomTypes = RoomTypeManager.GetAllRoomTypes(); 
    RoomTypes currentRoomType = RoomTypeManager.GetCurrentRoomType(); 
    bool isSelected = false; 
    foreach (RoomTypes roomTypes in roomTypes) 
    { 
    if (currentRoomType.Id == roomTypes.Id) 
     isSelected = true; 
    else 
     isSelected = false; 

    roomTypes.Add(new SelectListItem { Text = roomTypes.Name + " " +roomTypes.ColourCode, Value = roomTypes.Id, Selected = isSelected }); 
    } 

    ViewData["RoomTypes"] = roomTypes; 
+0

你宣佈roomTypesSelect但似乎並沒有用它做什麼? – JsonStatham 2015-03-06 12:01:14

相關問題