Search
Close this search box.

Passing Data to Master Pages with ASP.NET MVC

Friday, December 14, 2007 5:25 PM

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);
}
}

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.

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

Related Posts