mvc c# html.dropdownlist and viewbag

徘徊边缘 提交于 2019-12-03 17:50:12

问题


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.


回答1:


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");


来源:https://stackoverflow.com/questions/12112541/mvc-c-sharp-html-dropdownlist-and-viewbag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!