我正在学习在父操作中嵌入子操作,并在从子操作提交表单时正确呈现整个页面。
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(包含在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?
}
现在,当我点击“子按钮”时,我只会看到子动作的视图(durrr!),如何修复它以生成整页父+子视图?这似乎是一个很容易的逻辑,但我坚持了好几个小时。
答案 0 :(得分:2)
所以,如果我在HttpPost Details方法中删除了[ChildActionOnly], 当我单击提交时,只返回Details.cshtml partialView, 不是Master.cshtml,这不是我想要的,也不是。
那是因为在这种情况下你不应该返回一个PartialView,而是一个完整的View:
[HttpPost]
public virtual ActionResult Details(DetailsModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Success");
}
您可能还需要有条件地呈现Details
操作以避免无限循环:
@if (!IsPost)
{
@Html.Action("Details", "Home")
}
显然,如果你想保留你在调用这个POST动作时所处的原始上下文,你将不得不使用AJAX,然后用AJAX调用这个POST动作,并只替换DOM的相应部分。