6

Duplicate

Passing data to Master Page in ASP.NET MVC

Should an ASP.NET masterpage get its data from the view ?

I have been following this method for passing common data to the site.master. However, this does require specific casting of the ViewData and I don't like using string identifiers everywhere. Is this the best way to do it or is there another way?

http://www.asp.net/learn/MVC/tutorial-13-cs.aspx

Thanks

Community
  • 1
  • 1
Jon Archway
  • 4,852
  • 3
  • 33
  • 43

2 Answers2

8

You could create a base class that all your models inherit from:

class MasterModel {
     // common info, used in master page.
}

class Page1Model : MasterModel {
     // page 1 model
}

Then your master page would inherit from ViewMasterPage<MasterModel> and your Page1.aspx would inherit from ViewPage<Page1Model> and set Site.master as its master page.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
2

As I struggled a bit, here is my contribution :

class ModelBase {
     // common info, used in master page.
}

class Page1Model : ModelBase {
     // page 1 model
}

public class ControllerBase : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var model = ViewData.Model as ModelBase;

        // set common data here

        base.OnActionExecuted(filterContext);
    }
}
mathieu
  • 30,974
  • 4
  • 64
  • 90
  • This is also how I do it. Furthermore, you could throw an exception if model is not an instance of ModelBase, thereby ensuring that only valid models are passed to the view. – Erik Schierboom Feb 09 '11 at 10:21