mvc c# html.dropdownlist and viewbag

前端 未结 1 784
忘掉有多难
忘掉有多难 2021-02-08 17:42

So I have the following (pseudo code):

string selectedvalud = \"C\";
List list= new List();
foreach(var item in mymod         


        
1条回答
  •  迷失自我
    2021-02-08 17:51

    Try like this:

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

    and in your view:

    <%= Html.DropDownList(
        "Codes", 
        (IEnumerable)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");
    

    0 讨论(0)
提交回复
热议问题