[英]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.