#Render partial with a model in Layout View

爷,独闯天下 提交于 2019-12-12 05:27:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!