I have my class RoomType
:
Int32 Id
String Name
String ColorCode
My viewmodel gets a List<Roomtype> RoomTypes
which should be displayed in a dropdown.
Each dropdown option item should have: 1) as title the Name
, 2) as value the Id
, and 3) the style background-color #ColorCode
.
My problems are how to convert this list correctly into a List<SelectListItem>
as required by ASP.NET MVC's DropDownFor
helper, and then to have the correct values inserted for each option.
I've tried to have a new readonly property in my viewmodel, which has a getter RoomtypeSelectList
which returns new SelectList(RoomTypeList)
but I can't get the correct properties to show (Name, Id, Background color).
I'd appreciate some help or pointers in the right direction...
In the view try something like this
<%=Html.DropDownList("userList", new SelectList((IEnumerable)ViewData["RoomTypes"], "Value", "Text",selectedValue)) %>
in your controller action you'd have
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;
The built in html helper methods do not allow you to generate style or title attributes for the select list items.
If you want to add these attributes, you'll need to create your own html helper methods, or just output the select list manually using a <% foreach ... %>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With