Suppose I have a parent.cshtml view with a parentModel, and a child.cshtml view with a childModel.
This child action is [ChildActionOnly] and is rendered in parent.cshtml: @Html.Action("ChildAction").
Now, in controller/ParentAction
public ActionResult ParentAction() {return View();}
[HttpPost]
public ActionResult ParentAction(ParentModel parentmodel) {
if(!ModelState.IsValid) {
...
ModelState.AddModelError("", "parent view has an error");
}
return View(parentmodel); // pass the ball back to user
}
in controller/ChildAction
[ChildActionOnly]
public ActionResult ChildAction() {return View();}
[HttpPost]
public ActionResult ChildAction(ChildModel childmodel) {
if(!ModelState.IsValid) {
...
ModelState.AddModelError("", "child view has an error");
}
//??? return ParentView(parentmodel, childmodel) ??? how do i do this???
}
In the child action, how do I return to the ParentView (that also renders the ChildView), and preserve the data in their models?
EDIT:—–
My point is how not to do that. return View(childmodel); from child action will not get us what we want to see, because it will only give us a ‘partial’ page with child view only, the parent part is missing. RedirectToAction("ParentAction"); will give us full view again, but it will lose the models. Not sure how to handle returning models in nested views. That’s where I am stuck.
First you have to create a common model that wraps the
ParentModelandChildModelelse put theChildModelas a property of theParentModel. Instead of calling a child action and render the child view I would suggest you useHtml.RenderPartialin this case.Let say the
ParentModelwraps theChildModelthen from theParentView.cshtmlyou could renderthe ChildView.cshtmlby,Now from the child post action you have to build the
ParentModeland return theParentView.