ASP.net MVC Model Binding to a List of Objects always null

I had a View Model like this

public class MyViewModel
{
    public List<SelectedThings> Things
}

public class SelectedThings
{
    public long ThingId { get; set; }
    public bool Selected { get; set; }
}

Then in my view I was creating the markup like this:

@for (var i = 0; i < Model.Things.Count; i++)
{
    @Html.EditorFor(x => x.Things[i].Selected)
    @Html.HiddenFor(x => x.Things[i].ThingId)
}

Posting to a controller that looked like this:

[HttpPost]
public ActionResult MyController(MyViewModel model)
{
...
}

I could see the form was posting the data correctly and with the correct naming conventions. But in my controller the the SelectedThings was always null.

After several hours I managed to find the solution. In the view model it was as simple as changing SelectedThings from a public variable to a public property.

From

public List<SelectedThings> Things

To

public List<SelectedThings> Things { get; set; }

Posting it here in case it helps anyone else. And as a reminder for myself.

Leave a Reply

Your email address will not be published. Required fields are marked *