ListBoxFor not binding my viewmodel

2019-04-09 01:44发布

问题:

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>

回答1:

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)



回答2:

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(',');
}