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.ListBoxForcall to be for theSelectedCategoryIdsproperty.As an aside: Now that you are creating a list box for the
SelectedCategoryIdsproperty, if you have a label for the list you should change this to be for theSelectedCategoryIdsproperty too.(
"Categories"is the label text)