c# - 将我的 List<Roomtype> 转换为 SelectList for ASP。 NET MVC DropDownFor<>,并为每个选项项获取正确的值

标签 c# asp.net asp.net-mvc html-helper

我有我的课RoomType :

Int32 Id
String Name
String ColorCode

我的 View 模型得到一个 List<Roomtype> RoomTypes应该显示在下拉列表中。

每个下拉选项项应具有:1) 作为标题 Name , 2) 作为值 Id , 和 3) 样式背景色 # ColorCode .

我的问题是如何将此列表正确转换为 List<SelectListItem>根据 ASP.NET MVC 的要求 DropDownFor helper,然后为每个选项插入正确的值。

我尝试在我的 View 模型中添加一个新的只读属性,它有一个 getter RoomtypeSelectList返回 new SelectList(RoomTypeList)但我无法获得要显示的正确属性(名称、ID、背景颜色)。

我会很感激一些正确方向的帮助或指示...

最佳答案

在 View 中尝试这样的事情

 <%=Html.DropDownList("userList", new SelectList((IEnumerable)ViewData["RoomTypes"], "Value", "Text",selectedValue)) %>

在你的 Controller Action 中你会拥有

 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;

关于c# - 将我的 List<Roomtype> 转换为 SelectList for ASP。 NET MVC DropDownFor<>,并为每个选项项获取正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2952986/

相关文章:

javascript - 函数错误(){ [ native 代码]}

c# - 什么是 http 500 响应的 Thrift 等价物?

asp.net - 在ASP.NET中处理大文件上传时如何减少内存压力和线程使用?

c# - 如何在 asp.net mvc 中路由 "/"(默认 url)

c# - 将 JSON 数组从 c# 传递到 jQuery

c# - BoundedCapacity 是否包括当前正在 TPL 数据流中处理的项目?

c# - asp.Net 中 DateTime 的默认时区

c# - C# 和 ASP.NET 中的换行符有什么变化? (\r\n 与\n)

c# - 在 .NET MVC 中,我们可以将 CSS 保留在 Views 文件夹中吗?

c# - 不知道这样的主机,ClientDependency