tags:

views:

963

answers:

2

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

+6  A: 

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
Thanks, simple explanation! (saw this before but had trouble understanding it)
orip
A: 

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