MVC父子嵌套视图返回模型 [英] MVC parent and child nested views returning models
问题描述
假设我有一个带parentModel的parent.cshtml视图和一个带有childModel的child.cshtml视图.
此子操作为[ChildActionOnly]
,并呈现在parent.cshtml中:@Html.Action("ChildAction")
.
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")
.
现在,在控制器/ParentAction中
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
}
在控制器/ChildAction中
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???
}
在子操作中,如何返回ParentView(它也呈现ChildView),并将数据保存在其模型中?
In the child action, how do I return to the ParentView (that also renders the ChildView), and preserve the data in their models?
-----
我的意思是如何不这样做.子操作中的return View(childmodel);
无法获得我们想要看到的内容,因为它只会为我们提供仅具有子视图的部分"页面,而父部分丢失了. RedirectToAction("ParentAction");
将再次为我们提供完整视图,但将丢失模型.不确定如何在嵌套视图中处理返回的模型.那就是我被困住的地方.
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.
推荐答案
首先,您必须创建一个包装ParentModel
和ChildModel
的通用模型,否则将ChildModel
用作ParentModel
的属性.建议您在这种情况下使用Html.RenderPartial
而不是调用子操作并呈现子视图.
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.
假设ParentModel
包装了ChildModel
,然后从ParentView.cshtml
中渲染the ChildView.cshtml
,
Let say the ParentModel
wraps the ChildModel
then from the ParentView.cshtml
you could render the ChildView.cshtml
by,
@Html.Partial("ChildView", Model.ChildModel);
现在,从子发布操作中,您必须构建ParentModel
并返回ParentView
.
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);
}
这篇关于MVC父子嵌套视图返回模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!