Jash
Jash

Reputation: 962

asp.net mvc 6 model binding to complex collection - IList<T>

I am trying to do a post operation in asp.net mvc 6 and expecting the complex property collection to be initialized properly. But it is always empty.

I am creating input html element with proper index:

This is an HTML FORM for POST:

@model MainObject
<form asp-action="create" method="post">
  <input asp-for="ChildObjects[0].RollNumber" />
  <input type="submit" value="create" />
</form>

Controller Code

public async Task<IActionResult> Create(MainObject mainObj)
{
    // The mainObj.ChildObjects remains empty.
}

My view will contain only one child object entry, that's why only 0 index used.

The form data contains the above key and value but when it reaches the controller action the collection property is empty i.e. MainObject.ChildObjects has count 0. (Note: The ChildObjects list is already initialized in my MainObject constructor)

Models:

public class MainObject {
   public MainObject() {
      this.ChildObjects = new List<ChildObjects>();
   }

   public IList<ChildObject> ChildObjects {get; private set;}
}

On looking up the ModelState property in constructor in debug mode, it shows one Error for ChildObjects key, but the error message is too generic:

Object reference not set to instance of an object.

I have followed many articles on net for model binding complex collection, but somehow it is not working for me.

Upvotes: 4

Views: 5603

Answers (1)

Stafford Williams
Stafford Williams

Reputation: 9806

Declaring the child object collection with private set blocks the binder from setting the collection values. The setter must be public so MVC6 can set the values in the postback;

public IList<ChildObject> ChildObjects {get; private set;} // empty on postback
public IList<ChildObject> ChildObjects {get; set;} // populated on postback

The collection is still instantiated however (rather than null, and hence count == 0) when the model binder calls the parameterless constructor you have declared.

Upvotes: 8

Related Questions