A way to Pass data from an ASP.NET MVC View to the Master Page

I recommend

There is no clear cut mechanism provided by the ASP.NET MVC framework to pass data from a view to it’s master page. I’ve been using a technique that I’m reasonably happy with, which I’ll describe in this blog post.

For starters, my example will be using the ITypeInstanceDictionary provided in the TTC Tools. Please read my blog post pass data from an ASP.NET MVC controller to view to learn more. The code shown in this blog post is included in a demo web application on the TTC Tools GitHub page.

There are many scenarios in which you want to drive master page values from the view. For example: some CSS styling that exists in the master page will be dependent on the view. Personally I feel this should not be driven by the controller, as there are many situations in which CSS styles are purely display driven.

I’ll summarize the basic concepts for passing data from the view to it’s master page.

  • Create an interface that is used by the master page for use in the master page markup code, and allow the view to override these values.
  • Setup the master page view data at the top of the master page
  • Follow up the master page code with a content place holder.
  • This content place holder will be used by the view to override any master page data values.

My example code will show how to override the pages body element id in the master page from a view.

The following code snippet shows an example master page implementation:

Setup ASP.NET MVC Master Page To Allow View To Override Data

The view can override master page view data by creating a content control for the master page’s content place holder which follows the setup of the master page’s view data.

ASP.NET MVC View Pass Data To Master Page

The ASP.NET MVC view engine rendering execution flow will start at the top of the master page and then flow into the content place holders. This allows the view to override the master page view data before it is used later in the master page markup code.

I created a screen cast which might help explain this technique in a bit more detail.

If you need any further explanation or have any questions please let me know. I hope someone finds this useful :-)

Technical .NET ASP.NET MVC July 21, 2010


Comments