No Free Time

Because my therapist says I need to let things out

Archive for July 3rd, 2008

ASP.Net MVC: Giving MasterPages access to ViewData

Posted by Andrew Myhre on July 3, 2008

If you want to include ViewData in the MasterPage UI, you can.

ASP.Net MVC MasterPages are System.Web.Mvc.ViewMasterPage – this is a generic type just like System.Web.Mvc.ViewPage. So you can type it with a ViewData object, like this:

public partial class MyTemplate : ViewMasterPage<SomeViewData>

As soon as you do this you’re saying that the SomeViewData class is the only ViewData object that can be used on any page using this template. Not a problem though, just create a base ViewData class.

public class SiteWideViewData
{
}

public class PageViewData : SiteWideViewData
{
}

This of course means no more default ViewData objects and no more return View(); I found the easiest way to deal with that is to create a static property on the base ViewData:

public class SiteWideViewData
{
public static SiteWideViewData Default { get { return new SiteWideViewData(); } }
}

Now I can do this:

public ActionResult MySimpleControllerMethod()
{
return View(SiteWideViewData.Default);
}

And that seems to work okay.

Posted in .net, mvc | Tagged: , | 3 Comments »