How to pass viewmodel to a layout/master page?

╄→尐↘猪︶ㄣ 提交于 2021-02-17 21:30:55

问题


Having googling for some time, I'm a little bit confused with how to do this in asp mvc 3.

So, the task is to have a common layout (or master?) page for several controllers' views. All the views are strongly-typed themselves... This layout page in fact visualizes some strongly-typed object. So, I need this object to be passed to the layout page to pass it to `Html.RenderPartial()' or to render it right in the page.

The article Passing Data to View Master Pages (C#) (though an old one for mvc2) gives an example to provide a base abstract controller class, passing the model to ViewData. This could be the cure.

But...

In some threads I found a way one could make a strongly-typed master page:

<%@ Master ... Inherits="System.Web.Mvc.ViewMasterPage<MyWeb.Models.Client>" %>

So, is there the same approach in mvc3? Or the only way to pass data to a layout page is to use ViewBag or ViewData?

Having read what is the best way to bind ViewModel data to master page in asp.net-mvc, I've considered Darin's answer, but still think that this bunch of views will have the same layout, and see no reason to go against DRY principle.

So, how to pass strongly-typed objects to layout pages? Or have I mixed something up?


回答1:


It's an interesting debate topic -> passing view models to the master page / layout vs ViewBags.

I'm -hate- using ViewBags so I have view models for all my view-layers. Starting with the _layout.cshtml and upwards. Any view that uses a Layout .. well .. that view model just inherits the Layout .. or whatever view is below it .. and this is repeated until you hit the bottom level which is usually the _layout...

My RavenOverflow project has some sample code that shows this.

  • This is the the layout view, defined.
  • Here is the layout view model, defined.
  • This is the view that uses a layout.
  • Here is the view model, for that previous view.
  • This is some controller code, that creates the model .. which is then passed into the View.


来源:https://stackoverflow.com/questions/12946130/how-to-pass-viewmodel-to-a-layout-master-page

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