在Layout.cshtml中将ViewModel传递给Partial View调用 [英] Passing a ViewModel to a Partial View call in the Layout.cshtml
问题描述
背景
我正在尝试在正在使用的MVC应用程序上使用仪表板模板.
I am trying to make use of Dashboard template on an MVC application I'm working on.
我不确定如何将ViewModel传递给我称为Header的顶部栏.
I am not sure how I can pass a ViewModel to the top bar I've called Header.
代码
在我的_Layout.cshtml
中,我像这样分割了HTML:
In my _Layout.cshtml
, I have split the HTML like so:
<body class="">
@Html.Partial("_Header")
<div class="page-container row-fluid">
@Html.Partial("_Sidebar")
<div class="page-content">
<div class="content">
@RenderBody()
</div>
</div>
</div>
</body>
我猜这是错误的,因为现在我无法将ViewModel传递给标题部分,或者如果可以的话,我们不应该这样做吗?
I am guessing this is wrong because now I cannot pass a ViewModel to the header section, or if I can, we're not supposed to?
将其拆分的正确方法是什么?
What is the right way of splitting this?
推荐答案
使用@Html.Action()
或@{ Html.RenderAction(); }
代替@Html.Partial()
来调用[ChildActionOnly]
控制器方法,该方法将为仪表板初始化模型并返回部分信息.视图,例如
Instead of @Html.Partial()
, use @Html.Action()
or @{ Html.RenderAction(); }
to call a [ChildActionOnly]
controller methods that initializes your model for the dashboard and returns a partial view, for example
[ChildActionOnly]
public PartialViewResult Header()
{
// initialize a model
return PartialView("_Header", model)
}
并在布局中
@{ Html.RenderAction("Header", yourControllerName); }
另一种选择是,您在使用该布局的每个视图中使用的模型将需要一个属性,该属性是用于生成仪表板然后使用@Html.Partial("_Header", Model.yourDashBoardProperty)
The alternative is that the model you use in each view using that layout would need a property which is the model used to generate your dashboard and then use @Html.Partial("_Header", Model.yourDashBoardProperty)
这篇关于在Layout.cshtml中将ViewModel传递给Partial View调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!