Reputation: 16236
I am learning to embed a child action inside a parent action, and render the whole page properly when a form is submitted from the child action.
ParentAction.cshtml--------------------------------------
@model Web1.Models.ParentActionModel
@{ViewBag.Title = "ParentAction";}
<h2>Parent Action</h2>
@Html.ValidationSummary(true, "Please correct parent errors and try again.")
@using (Html.BeginForm()) {
//parent forminput stuff
<input type="submit" value="Parent Button" />
}
@Html.Action("ChildAction","Home") <!-- ChildAction is included here -->
ChildAction.cshtml (included in parent.cshtml) ------------
@model Web1.Models.ChildActionModel
@{ViewBag.Title = "ChildAction";}
<h2>Child Action</h2>
@Html.ValidationSummary(true, "Please correct child errors and try again.")
@using (Html.BeginForm("ChildAction", "Home")) {
//child form input stuff
<input type="submit" value="Child Button" />
}
HomeController.cs-----------------------
public ActionResult ParentAction() {
return View();
}
[HttpPost]
public ActionResult ParentAction(ParentActionModel pmodel) {
//do model update stuff
return View(pmodel);
}
[ChildActionOnly]
public ActionResult ChildAction() {
return PartialView();
}
[HttpPost]
public ActionResult ChildAction(ChildActionModel cmodel) {
//do model update stuff
return PartialView(cmodel); // <---This is wrong, What's the correct way to do it?
}
Now, when I click the "Child Button", I will only get the view of the child action (durrr!), how do I fix it to generate full page parent+children view? It seems like a logic easy enough, but I am stuck on it for hours.
Upvotes: 0
Views: 2525
Reputation: 1038730
So, if I removed the [ChildActionOnly] in HttpPost Details method, when I click submit, only the Details.cshtml partialView is returned, not with the Master.cshtml, which is not what I want, neither.
That's because you should not return a PartialView in this case, but a full View:
[HttpPost]
public virtual ActionResult Details(DetailsModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Success");
}
You might also need to only conditionally render the Details
action to avoid infinite loops:
@if (!IsPost)
{
@Html.Action("Details", "Home")
}
Obviously if you want to preserve the original context you were in when you invoked this POST action, you will have to use AJAX and then invoke this POST action with AJAX and replace only the corresponding part of the DOM.
Upvotes: 2