views:

2414

answers:

3

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.

A: 

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!

rokeyge
A: 

Hi,

Was interested in your post here about multi-select values being returned.

How do you go about updating your model with the new comma seperated values from the ID values?

Do you simply clear the current stored values and re-insert the newly selected values?

Just interested...!

Thank You! Paul

Paul Hinett
A: 

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.

Sohnee