Asp.net mvc MVC父嵌套视图和子嵌套视图返回模型
假设我有一个带有parentModel的parent.cshtml视图,和一个带有childModel的child.cshtml视图。 此子操作是Asp.net mvc MVC父嵌套视图和子嵌套视图返回模型,asp.net-mvc,Asp.net Mvc,假设我有一个带有parentModel的parent.cshtml视图,和一个带有childModel的child.cshtml视图。 此子操作是[ChildActionOnly]并在parent.cshtml:@Html.action(“ChildAction”)中呈现 现在,在控制器/父操作中 public ActionResult ParentAction() {return View();} [HttpPost] public ActionResult ParentAction(Par
[ChildActionOnly]
并在parent.cshtml:@Html.action(“ChildAction”)
中呈现
现在,在控制器/父操作中
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
}
控制者/儿童行动中
[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???
}
在子操作中,我如何返回到父视图(它也呈现子视图),并将数据保留在它们的模型中
编辑:-----
我想说的是如何避免这样做<代码>返回视图(childmodel)from child action将无法获得我们想要看到的内容,因为它只会为我们提供一个仅包含子视图的“部分”页面,缺少父部分<代码>重定向到操作(“父操作”)将再次为我们提供完整视图,但它将丢失模型。不确定如何处理嵌套视图中返回的模型。这就是我被困的地方 你根本不知道。为什么要在子操作中返回父模型?每个操作都将处理自己的模型首先,您必须创建一个通用模型来包装
父模型
和子模型
,否则将子模型
作为父模型
的属性。在本例中,我建议您使用Html.RenderPartial
,而不是调用子操作并呈现子视图
假设ParentModel
包装ChildModel
,然后从ParentView.cshtml
可以通过
@Html.Partial("ChildView", Model.ChildModel);
现在,从子post操作开始,您必须构建ParentModel
,并返回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);
}
尝试将您的childModel作为父模型的子模型。将childModel传递给子控制器,然后在父控制器中忽略它。@Aleksey:child.cshtml中有一个表单和一个提交按钮,用于发布有关childModel的信息。[HttpPost]public ActionResult ChildAction(ChildModel ChildModel){…所以,我不明白你的观点,ParentModel是如何围绕ChildModel的?请你展示一下代码示例好吗?也可能正如themarcuz所说,每个人都处理自己的模型?我知道我们不这样做。但我不能把它作为一个答案。我的观点是如何不这样做。返回视图(childmodel);from child action不会得到我们想要看到的内容,因为它只会给我们一个仅包含子视图的“部分”页面,缺少父部分。RedirectToAction(“ParentAction”);将再次提供完整视图,但它将丢失模型。不确定如何处理嵌套视图中的返回模型。这就是我遇到的问题。看起来mvc中的“customControl”不像asp.net web表单那样简单。此返回视图/partialview结构相当扁平,在ajax更新dom对象时效果更好。