问题
I have a MVC project where I want to render my menu using Model.
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.
I cannot simply use @Html.Partial("_Menu")
inside my _Layout.cshtml
And if I do @Html.Partial("_Menu", Model.Something)
, I get a
Object reference not set to an instance of an object
error on the Model.
回答1:
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)
).
Hope that helps.
回答2:
You can use Razor - Section for this:
Inside _Layout.cshtml:
<div id=”menu”>
@RenderSection("Menu", required:false)
</div>
& On the pages (Eg. Index.cshtml) you want Menu:
@section Menu
{
@Html.Partial("_Menu", Model.Something)
}
回答3:
Provide more details:
- Why you are using
Session_Start
? - How you filling model
Model.Something
?
The simplest way for creating dynamic menu is @Html.RenderAction
.
来源:https://stackoverflow.com/questions/12722320/render-partial-with-a-model-in-layout-view