How to pass viewmodel to a layout/master page?

horgh picture horgh · Oct 18, 2012 · Viewed 12.3k times · Source

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?

Answer

Pure.Krome picture Pure.Krome · Oct 18, 2012

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.