MVC ModelBind ListBox With Multple Selections

2019-06-04 23:14发布

How do I submit the ListBox selections to the ModelBinder?

<%=Html.Hidden("response.Index",index)%>
<%=Html.ListBox("response[index].ChoiceID",
                new MultiSelectList(gc.choice,"ChoiceID","ChoiceText") )%>

'gc.choice' is a List

I can get the fisrt selected value to the model, but not the second selection presumably because I cannot change the index.

2条回答
Juvenile、少年°
2楼-- · 2019-06-04 23:35

I have solved this in a slightly different way...

[Model]
public IEnumerable<string> SelectedStores { get; set; }

[View]
<%= Html.ListBox("SelectedStores", 
    (MultiSelectList)ViewData["Stores"], 
    new { size = "8" }) %>

[Controller]
ViewData["Stores"] = 
    new MultiSelectList(StoreItems, "Value", "Text", model.SelectedStores);

So the model has an IEnumberable that will be populated with the user-selections. The view displays the ListBox with the MultiSelectList and the controller passes in the SelectedStores from the model when it constructs the MultiSelectList.

查看更多
淡お忘
3楼-- · 2019-06-04 23:50

I built a presentation model SamplePresentationModel class that has a MultiSelect member userList. Then suppose IEnumerable<User> allUser is the list of options. I use

  View(new SamplePresentationModel(){ userList = new MultiSelectList(allUsers, 
    "UserId", 
    "UserName", 
    allUsers.Select(user => user.UserID))});

to pass the MultiSelection to the view.

Then in the view I can construct the listbox

   <label for="userList">users:</label>
    <%= Html.ListBox("usersList", Model.userList)%>

In the POST action I can capture the selections:

IEnumerable<int> selectedUserIDs = Request["usersList"].Split(new Char[] { ',' }).Select(idStr => int.Parse(idStr));

Don't know if this helps!

查看更多
登录 后发表回答