我有我的课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/