#在布局视图中使用模型渲染局部模型 [英] #Render partial with a model in Layout View
问题描述
我有一个MVC项目,我想在其中使用Model渲染菜单.
I have a MVC project where I want to render my menu using Model.
我在Global.asax.cs的Session_Start
事件中声明菜单内容,并使用断点知道该菜单正确填写了.
I declare the menu contents at the Session_Start
event in Global.asax.cs and using break point i knew that it is filling out correctly.
我不能简单地在我的_Layout.cshtml
如果我执行@Html.Partial("_Menu", Model.Something)
,我会得到
对象引用未设置为对象的实例
Object reference not set to an instance of an object
模型错误.
推荐答案
首先,我建议不要使用session对象,但是由于您正在使用它,因此请在从您那里继承的所有控制器将从会话中获取菜单数据,并将其推入视图包.然后,在_Layout中,您可以从视图包(
First off I would recommend against the session object, but since you're using it then in the Initialize method (override) of a common controller that ALL controllers inherit from you'll grab the menu data from the session, and push it into the viewbag. Then in the _Layout you can retrieve the object from the viewbag (
var navigationItems = ViewBag.NavigationItems as NavigationViewModel;
)作为字段,并将该对象或其属性传递到局部以进行渲染(
) as field and use that object anywhere by passing it or a property of it to a partial for rendering (
@Html.Partial("_Navigation", navigationItems)
).
希望有帮助.
这篇关于#在布局视图中使用模型渲染局部模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!