Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc c# html.dropdownlist and viewbag

So I have the following (pseudo code):

string selectedvalud = "C";
List<SelectListItem> list= new List<SelectListItem>();
foreach(var item in mymodelinstance.Codes){
  list.Add(new SelectListItem { Text = item.Name, Value = item.Id.Tostring(), Selected = item.Id.ToString() == selectedvalue ? true : false });
}

ViewBag.ListOfCodes = list;

on my view:

<%: Html.DropDownList("Codes", (List<SelectListItem>)ViewBag.ListOfCodes , new { style = "max-width: 600px;" })%>

now, before it reaches the view, the "list" has populated it with items and has marked the item which is already selected. but when it gets to the view, none of the options are marked as selected.

my question is, is it possible to use a viewbag to pass the items or should i use a different medium? as it removes the selected flag on the options if i use it that way.

like image 233
gdubs Avatar asked Aug 24 '12 15:08

gdubs


1 Answers

Try like this:

ViewBag.ListOfCodes = new SelectList(mymodelinstance.Codes, "Id", "Name");
ViewBag.Codes = "C";

and in your view:

<%= Html.DropDownList(
    "Codes", 
    (IEnumerable<SelectListItem>)ViewBag.ListOfCodes, 
    new { style = "max-width: 600px;" }
) %>

For this to work you obviously must have an item with Id = "C" inside your collection, like this:

    ViewBag.ListOfCodes = new SelectList(new[]
    {
        new { Id = "A", Name = "Code A" },
        new { Id = "B", Name = "Code B" },
        new { Id = "C", Name = "Code C" },
    }, "Id", "Name");
like image 193
Darin Dimitrov Avatar answered Sep 28 '22 12:09

Darin Dimitrov