Passing Data to Master Pages with ASP.NET MVC

There is a discussion occurring on the ASP.NET forums about passing data to Master Pages using ASP.NET MVC.  I couldn't figure out how to post code in the forums, so this post contains an example of the solution I am currently using.

I defined a "container" class that contains the data for the specific view and the data needed by the master page.  It looks like this:

public class ViewDataContainer
{ public ITopMenuData TopMenu { get; set; } public ILeftMenuData LeftMenu { get; set; } public T Data { get; set; }
}

As you can see, this class is generic on the type of view data that it contains.

Next, I created a custom Controller-derived class that looks like this:

public class ControllerBase : Controller { protected override void RenderView(string viewName, string masterName, object viewData)
{ ViewDataContainer container = new ViewDataContainer
{
TopMenu = new TopMenuData(),
LeftMenu = new LeftMenuData(),
Data = (T)viewData
}; base.RenderView(viewName, masterName, container);
}
}

This class takes the view data that's passed in by the controller and wraps it up in an instance of ViewDataContainer that is then passed along.  As to where to get the TopMenuData and LeftMenuData, I'm still working on that :).

In this incarnation, views need to derive from ViewPage<ViewDataContainer> (specifying T) and then access their view data via the ViewData.Data property.  Today I was playing around with a ViewPage derived class that would expose the typed view data directly.  Maybe I'll post that soon as well.

This article is part of the GWB Archives. Original Author: Sean Carpenter

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.