Tom
Tom

Reputation: 16256

MVC parent and child nested views returning models

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.

Upvotes: 2

Views: 5292

Answers (2)

VJAI
VJAI

Reputation: 32768

First you have to create a common model that wraps the ParentModel and ChildModel else put the ChildModel as a property of the ParentModel. Instead of calling a child action and render the child view I would suggest you use Html.RenderPartial in this case.

Let say the ParentModel wraps the ChildModel then from the ParentView.cshtml you could render the ChildView.cshtml by,

@Html.Partial("ChildView", Model.ChildModel);

Now from the child post action you have to build the ParentModel and return the ParentView.

[HttpPost] 
public ActionResult ChildAction(ChildModel childmodel) { 
    if(!ModelState.IsValid) 
    {
       ...
       ModelState.AddModelError("", "child view has an error");
    } 

    ParentModel model = .. build the model from querying database.

    return View("ParentView", model);
}

Upvotes: 2

themarcuz
themarcuz

Reputation: 2583

Simply you don't. Why should you return the parent model in the child action? Every action will handle its own model

Upvotes: 0

Related Questions