ASP.NET MVC MultiSelectList with selected values not selecting properly

后端 未结 6 1159
猫巷女王i
猫巷女王i 2020-12-02 17:09

I know others have asked this question, but I\'m totally confused by this:

This displays the dropdown with no values selected:

<%= Html.DropDownLi         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 18:10

    I had a similar problem, when using ListBoxFor and a MultiSelectList assigned as a ViewBag property. @jero's answer helped me figure out that if there's a naming collision between the ViewBag field and the model field, then the selected values don't appear properly.

    If I did the following, the items did not show up as selected.

    //Controller
    ViewBag.SelectionIds = new MultiSelectView(possibleValues, "Value", "Name", selectedValues);
    
    //View
    @Html.ListBoxFor(model => model.SelectionIds, (MultiSelectList)ViewBag.SelectionIds, new { @class = "form-control" })
    

    If I changed it to the following, then it was fine.

    //Controller
    //Changed ViewBag.SelectionIds to ViewBag.SelectionIdList
    ViewBag.SelectionIdList = new MultiSelectView(possibleValues, "Value", "Name", selectedValues);
    
    //View
    @Html.ListBoxFor(model => model.SelectionIds, (MultiSelectList)ViewBag.SelectionIdList, new { @class = "form-control" })
    

提交回复
热议问题