Three Value Logic Three Value Logic - 2 years ago 122
C# Question

MVC Post A Child model to a Controller

I have a parent view model (Let's call it ParentViewModel) which has a list of children view models (Let's call them ChildViewModel). Each child view model can be edited independently and I have a separate form which I display in a loop. This works brilliantly but I cannot work out how to post just the child model and ignore the parent.

This is my form:

@model ParentViewModel


...

@foreach (var child in Model.Children)
{
@using (Html.BeginForm("_EditChild", "Admin", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.EditorFor(model => child.Content, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => child.Content, "", new {@class = "text-danger"})
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" value="Create" class="btn btn-default new-post" />
</div>
</div>
}
}


And this is the signature of my controller. It is expecting a type ChildViewModel which exists in ParentViewModel as a list.

[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _EditPost([Bind(Include = "")] ChildViewModel childViewModel)
{

}


The form works and submits BUT ChildViewModel is null when it reaches the submit controller. This is certainly because binding between the Form Post and the Action is not happening.

Answer Source

I am afraid it is not possible to post the child model only , since the page can define one and only one model that is the parent model you have defined .

But you can solve your problem simply by posting the parent model and extracting the child model in the controller .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download