list= new List

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; 

in my opinion:

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

now, before it reaches the view, the "list" has filled it with elements and marked the element that is already selected. but when it gets to the view, none of the options will be marked as selected.

My question is, can I use a viewing bag to transfer items or use a different medium? as it removes the selected flag in the options if I use it that way.

+8
asp.net-mvc html-select viewbag html.dropdownlistfor
source share
1 answer

Try it like this:

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

and in your opinion:

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

To do this, you obviously must have an element with Id = "C" inside your collection, for example:

  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"); 
+21
source share

All Articles