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.
asp-foris suspect, you probably wantvalue=Model.ChildObjects[0].RollNumber. But if you've got an empty reference, you need to post your controller code where you are instantiating this MainObject and forwarding it to the view also.asp-foris MVC6 (or MVC core if you like) syntax for tag helpers.<label>, however I see here that it does also go in the<input>.return View(mainObj)