Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert my List<Roomtype> to SelectList for ASP. NET MVC DropDownFor<>, and get the correct values per option item

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...

like image 264
Alex Avatar asked Jun 01 '10 20:06

Alex


2 Answers

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;
like image 88
Luke Avatar answered Sep 20 '22 14:09

Luke


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 ... %>.

like image 33
womp Avatar answered Sep 19 '22 14:09

womp