Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass viewmodel to a layout/master page?

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?

like image 554
horgh Avatar asked Oct 18 '12 02:10

horgh


1 Answers

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.
like image 82
Pure.Krome Avatar answered Oct 02 '22 03:10

Pure.Krome