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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.