4

How to pass a model to the MVC 3 Razor "masterpage"?

Razor view engine is different from the aspx view engine.

help0001
  • 41
  • 1
  • 3
  • Dup? http://stackoverflow.com/questions/78548/passing-data-to-master-page-in-asp-net-mvc – Martin Dec 09 '10 at 15:38
  • No, it's not the same, because the Razor view engine works different than the aspx view engine. There is the _ViewStart.cshtml and the _Layout.cshtml – help0001 Dec 09 '10 at 15:45
  • It's not the same, but it still includes advice that could help... see my answer below – Mark van Proctor Dec 10 '10 at 00:31

4 Answers4

6

The layout page will "inherit" the model of the content page. Are you trying to have the layout page have a different model than the content page?

marcind
  • 52,944
  • 13
  • 125
  • 111
  • Not sure about help001, but I would like to do that. I have a status bar in the master that I always want to display some info from the highest level of the model (call it Product). Individual views have models like Product.Parts, Product.Contractors, etc. Since they can all get to Product, I was hoping to pass that "up" to the master. – James in Indy Aug 05 '11 at 12:26
2

I'm not sure whether the _Layout.cshtml can have a separate model.

Perhaps would you should look into is a M-V-VM configuration with ViewModels that inherit from a BaseViewModel class that provides the necessary shared data required for the _Layout.cshtml "MasterPage".

Great info on MVVM here: Stack Overflow: MVVM ViewModel vs MVC ViewModel. Also info on pushing shared ViewModel functionality into a base class here: Stack Overflow: Push Common ViewModel functionality into a base class?

[Update] The link in Martin's initial comment, whilst not representing a direct duplicate of your issue, does include some info on how to inject the base ViewModel functionality without the Controller's needing to know anything about it... re-link here: Stack Overflow: Passing Data to Master Page in ASP.Net MVC

Community
  • 1
  • 1
Mark van Proctor
  • 733
  • 7
  • 13
1

There is no difference between view engine because Model is not a part of presentation layer. Use base application controller to create and fill shared model and pass reference to it into ViewBag property of request context. Read:

Passing Data to View Master Pages - an ASP.NET tutorial

ViewBag dynamic in ASP.NET MVC 3

Kuvalda.Spb.Ru
  • 443
  • 4
  • 6
-3
public ActionResult Test(TestModel model)
{
}

TestModel is a model class.. Like this you can pass model to master page

Tisho
  • 8,320
  • 6
  • 44
  • 52
Arun Raj
  • 1
  • 2