代码之家  ›  专栏  ›  技术社区  ›  Alex

将my list<roomtype>转换为selectlist for asp。NET MVC DropDownfor<>,并获取每个选项的正确值

  •  5
  • Alex  · 技术社区  · 16 年前

    我有我的班 RoomType :

    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 回复  |  直到 16 年前
        1
  •  2
  •   womp    16 年前

    内置的HTML助手方法不允许为选择列表项生成样式或标题属性。

    如果要添加这些属性,则需要创建自己的HTML助手方法,或者只需使用 <% foreach ... %> .

        2
  •  9
  •   Luke    16 年前

    在视图中尝试类似的操作

     <%=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;