Geeks With Blogs
Sean Carpenter Thoughts on Development

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<T>
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<T> : Controller
protected override void RenderView(string viewName, string masterName, object viewData)
ViewDataContainer<T> container = new ViewDataContainer<T>
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<T> 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<T>> (specifying T) and then access their view data via the ViewData.Data property.  Today I was playing around with a ViewPage<T> derived class that would expose the typed view data directly.  Maybe I'll post that soon as well.

Posted on Friday, December 14, 2007 5:25 PM | Back to top

Comments on this post: Passing Data to Master Pages with ASP.NET MVC

# re: Passing Data to Master Pages with ASP.NET MVC
Requesting Gravatar...
Interesting solution, i'll use it for now.

Phil Haack promises more natural way to do this by the next CTP, would be nice to see how they implement it.

Left by uzmobile on Dec 15, 2007 12:17 AM

Comments have been closed on this topic.
Copyright © Sean Carpenter | Powered by: