0

我正在学习在父操作中嵌入子操作,并在从子操作提交表单时正确呈现整个页面。

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!),如何修复它以生成整页父+子视图?这似乎是一个很简单的逻辑,但我坚持了几个小时。

4

1 回答 1

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 的相应部分。

于 2012-06-22T09:52:32.300 回答