In my MVC project, I am having issue with binding MultiSelectLists with my Model properties. Although I can get the values through FormCollection object, but those are just the Selected IDs.
Following is my Model Class which represents a Post.
public class PostModel
{
[Required(ErrorMessage = "Id is a required field")]
public int Id { get; set; }
[Required(ErrorMessage = "Post Title is required")]
[StringLength(500)]
public string Title { get; set; }
.......
public SelectList UnassignedTags { get; set; }
public SelectList AssignedTags { get; set; }
}
Please note that this is just a Model class and has two additional properties (UnassignedTags and AssignedTags) only for the purpose of displaying them on screen and for keeping the values bound between calls.
A Single Post can be marked with multiple Tags. On my View, I want two multi select Lists. One to hold Unassigned Tags (Text and Value) and other to Hold Assigned Tags (Text and Value).
On My view, I show a Multi Select list for these lists using following code.
@Html.ListBox("UnassignedTagss", Model.UnassignedTags, new { @class = "form-control" })
@Html.ListBox("AssignedTagss", Model.AssignedTags, new { @class = "form-control" })
Everything is ok when I load the record on screen.
Once loaded, I let user move items between lists through javascript.
The problem comes when Form gets posted back for editions. I am unable to bind Listbox values with my model properties.
Following are my Action Methods for Showing / Editing Post record.
public ActionResult PostDtls(int postId)
{
…..
}
[HttpPost]
public ActionResult PostDtls(PostModel post, FormCollection collection)
{
…….
}
Is there any way I can bind ListBox items (regardless of selected or not) to my Model SelectList properties i.e. UnAssignedTags and AssignedTags ?
At the moment, I am selecting all items of ListBox through JQuery before posting the form back to the server. This way, I get comma separated Ids in FormCollection Object. However, the problem is that if I have to redisplay the view to the user because of an Invalid ModelState, I have to fetch the Tags from the database based on the Ids available in FormCollection object. I know the above solution is bad. And I need to know a good approach to implement this requirement.