9

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.

gdubs
  • 2,724
  • 9
  • 55
  • 102
  • Can you breakpoint in your controller and double check that at least one item of `list` has been tagged as `Selected = true;`? I don't think ViewBag is messing with your list. – StuartLC Aug 24 '12 at 15:46
  • yes i did that and it is marking the right option. – gdubs Aug 24 '12 at 15:48

1 Answers1

22

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");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • which part of this selects "Code C"? – gdubs Aug 24 '12 at 15:50
  • 1
    This one: `ViewBag.Codes = "C";`. And since in the view you used Codes as first argument to your `DropDownList` helper it will pick the value from ViewBag. Obviously things could have been a million times more clear if you had used a view model and a strongly typed `DropDownListFor` helper and forgot about ViewBag which is what I always recommend to people. – Darin Dimitrov Aug 24 '12 at 15:52
  • i agree, i would do that too. but in this scenario, the value from this list will be appended to another value of another dropdownlist which will end up being written on the instance. i wish it was modeled differently.. – gdubs Aug 24 '12 at 16:38
  • 1
    i'm surprised that worked. was wondering, how the object picked the value up? so does that mean if the ViewBag is the same as the "name" of the object(textbox,radiobutton,etc) then it uses the value passed? or does it only work for dropdownlists?? – gdubs Aug 24 '12 at 16:49