No Free Time

Because my therapist says I need to let things out

ASP.Net MVC: Giving MasterPages access to ViewData

Posted by andrewmyhre 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.

3 Responses to “ASP.Net MVC: Giving MasterPages access to ViewData”

  1. [...] ASP.Net MVC: Giving MasterPages access to ViewData (7/2/2008)Wednesday, July 02, 2008 from andrewmyhre.wordpress.comIf you want to include ViewData in the MasterPage UI, you can. ASP. Net MVC MasterPages are System. Web. Mvc…. [...]

  2. [...] ASP.Net MVC: Giving MasterPages access to ViewData (7/2/2008) [...]

  3. andrewmyhre said

    such as?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>