I know tis question has been asked quite allot on SO.
But I still can't figure out the problem.
I am developing a blog to teach myself the MVC framework. Now when I post the view below, The ListBoxFor helper does not bind any values to my model. The list successfully contains all the categories but when the POST controller gets back the view model the Categories object is null.
Here is the View Model:
public class PostViewModel
{
public Post Posts { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
The Controller:
public ActionResult Create()
{
PostViewModel post = new PostViewModel();
post.Categories = db.ListCategories();
return View(post);
}
The View:
<p>@Html.ListBoxFor(model => model.Categories, new MultiSelectList(Model.Categories, "CategoryID", "CategoryName"))</p>
I believe you should have an array property in your view model which the selected IDs will bind to.
And change your
Html.ListBoxFor
call to be for theSelectedCategoryIds
property.As an aside: Now that you are creating a list box for the
SelectedCategoryIds
property, if you have a label for the list you should change this to be for theSelectedCategoryIds
property too.(
"Categories"
is the label text)Not 100% sure if I understand your question; but does this code help? It shows how you can fetch which categories were selected when posting the form back to the server.