如何将数据传递到布局中的 PartialView?
我有一个 _layout.cshtml 包含这一行:
@{Html.RenderPartial("Menu");}
现在我想将模型传递到此 RenderPartial 函数中。该模型可以从我的存储库中读取。
如何以及在哪里(在代码中)可以完成此操作?
谢谢!
I have a _layout.cshtml containing this row:
@{Html.RenderPartial("Menu");}
Now I want to pass in a model into this RenderPartial-function. This model can be read from my repository.
How and where(in code) can this be done?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
RenderPartial 有一个重载,可以将对象发送到局部视图。
不要忘记在局部视图的顶部定义 @model 以使用正确的对象类型。
@Html.RenderPartial("ViewName",object)
额外信息: MSDN
评论后编辑:
我认为创建一个接受存储库的 MenuController 会更容易。然后让它创建一个视图,该视图将所需的存储库作为模型,然后使用 foreach 将每个菜单项渲染为操作链接,并将菜单信息传递给它。
所以你会在你的 _layout.cshtml 中包含这个:
在你的 MenuController 中: 这个
在你的 MenuView 中:
这会更接近解决方案吗?
RenderPartial has an overload that can take an object to send it to the partial view.
Don't forget to define your @model at the top of your partialview to work with the right object type.
@Html.RenderPartial("ViewName",object)
Extra info: MSDN
Edit after comment:
I think it would be easier to create a MenuController that takes in the repository. Then let it create a view which takes in the required repository as it's model, then with a foreach render every menu-item as actionlinks, passing the menu info to it.
So you would have this in your _layout.cshtml:
This in your MenuController:
And your MenuView:
Would that be any closer to a solution?
还有另一种解决方案将数据传递到布局中的部分视图。您可以简单地将其添加到 _Layout.cshtml 文件
和 Controller 中:
ChildActionOnly
属性确保操作方法只能作为子方法调用。此操作将在布局中使用模型渲染相应的部分视图。There is another solution as well to pass data to a partial view in Layout. You can simply add this in your _Layout.cshtml file
And in your Controller :
The
ChildActionOnly
attribute ensures that an action method can be called only as a child method. This action will render the corresponding partial view with model in Layout.