My view:
<div class="editor-label">
@Html.LabelFor(model => model.UserList)
</div>
<div class="editor-field">
@Html.ListBoxFor(model => model.SelectedUsers, new MultiSelectList(Model.UserList, "Key", "Value", Model.SelectedUsers))
@Html.ValidationMessageFor(model => model.UserList)
</div>
My viewmodel:
public class UserListViewModel
{
public UserListViewModel() :
this(new List<KeyValuePair<string, string>>())
{
}
public UserListViewModel(IList<KeyValuePair<string, string>> userList)
{
this.UserList = userList;
SelectedUsers = new List<string>();
}
public IList<KeyValuePair<string,string>> UserList { get; set; }
public IList<string> SelectedUsers { get; set; }
}
As it is now I only get the selected values and when I reach the controller my UserList is emptied so I can’t compare with that again. Is there any way I can return both the value and the text from the MultiSelectList or at least remember the contents of my UserList until I reach the controller?
The
Html.ListBoxForhelper renders a<select>element with themultipleattribute. In HTML when you place this tag in a form and submit the form only the selected values are sent to the server. That’s how HTML works. If you want to send the text as well you will have to use javascript. For example you could subscribe to the change event of the select element and then keep a hidden field inside the form that will be update with the list of the selected texts. But honestly don’t do that. In your POST controller action simply fetch the texts from the same location you fetched them in your GET action to display the form initially.