Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBoxFor not binding my viewmodel

I know tis question has been asked quite allot on SO.

here and here

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>
like image 752
RaVen Avatar asked Nov 01 '11 12:11

RaVen


2 Answers

I believe you should have an array property in your view model which the selected IDs will bind to.

public class PostViewModel
{
    public Post Posts { get; set; }
    public int[] SelectedCategoryIds { get; set; }
    public IEnumerable<Category> Categories { get; set; }
}

And change your Html.ListBoxFor call to be for the SelectedCategoryIds property.

<p>@Html.ListBoxFor(model => model.SelectedCategoryIds, new MultiSelectList(Model.Categories, "CategoryID", "CategoryName"))</p>

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 the SelectedCategoryIds property too.

@Html.LabelFor(model => model.SelectedCategoryIds, "Categories")

("Categories" is the label text)

like image 52
dan Avatar answered Nov 18 '22 18:11

dan


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.

[HttpPost]
public ActionResult Create(Post post, FormCollection formCollection) 
{
  var listOfCategoryIDs = formCollection["categories"];
  var arrayOfCategoryIDs = listOfCategoryIDs.Split(',');
}
like image 2
KBoek Avatar answered Nov 18 '22 17:11

KBoek