[英]Pass a value to a partial view from parent view
我有一个 Web 应用程序,其中我的控制器将模型传递给父视图,如下所示:
public ActionResult Results()
{
//Processing
return View ("ParentView",model);
}
在我的“ParentView”中,我将渲染一个局部视图,如下所示:
@Html.Partial("_PartialView", anotherModel)
现在我根本不想碰anotherModel
。
但我想要做的是从ParentView
向_PartialView
传递一个值。
我知道我可以将ViewBag.Value="Text"
从 Controller 传递给"ParentView"
,但是从"ParentView"
到"_PartialView"
是否可行?
基本上我想在"ParentView"
正在使用的model
中添加一个值,并以某种方式将其传递给"_PartialView"
您可以将属性从PageView
模型传递到PartialView
如下所示:
@Html.Partial("_PartialView", @Model.AnotherModel)
然后,设置你的的型号_PartialView
是类型的AnotherModel
。
您必须创建一个视图模型。 您可以通过 3 种方式创建它
第一种方式
public class ViewModel
{
public class ParentViewModel {get; set;}
public class ChildViewModel {get; set;}
}
在这种情况下,您的观点
@model ViewModel
...... //html is using @Model.ParentViewModel)
@Html.Partial("_PartialView", @Model.ChildViewModel)
第二种方式
public class ParentViewModel:ChildViewModel
在这种情况下,相同的模型可用于两者
@model ParentViewModel
...... //html is using @Model)
@Html.Partial("_PartialView")
如果可以使用另一个模型的接口,则可以使用第三种方式
局部视图
@model IAnotherModel
视图模型
public class ViewModel:IAnotherModel
视图与第二种方式相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.