mvc c# html.dropdownlist and viewbag
Asked Answered
O

1

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.

Outage answered 24/8, 2012 at 15:40 Comment(2)
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.Caffrey
yes i did that and it is marking the right option.Outage
E
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");
Emelinaemeline answered 24/8, 2012 at 15:45 Comment(4)
which part of this selects "Code C"?Outage
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.Emelinaemeline
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..Outage
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??Outage

© 2022 - 2024 — McMap. All rights reserved.