How to change master page for a specific view with Asp.Net MVC<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to change master page for a specific view with Asp.Net MVC

Posted on: June 17, 2012

You may want to have a specific master page for a specific page. This can be handled in many way.

The first way is the simplest and can be good enough for few pages that need a specific master page. This is done by returning the view with the master page parameter.

1public ActionResult Index() {
2 return View("Index", "MasterPageCustom");

You could also use the View object and setting the master page name with a setter.

1public ActionResult SomeOtherPage() {
2 var view = View("Index");
3 view.MasterName = "MasterPageCustom";
4 return view;

Generally, if you have a bigger website, you would prefer to handle master page at a higher level like the controller. This can be done by using the OnActionExecuted. Right after the action is executed, the controller can change the master page of the returned view.

1protected override void OnActionExecuted(ActionExecutedContext filterContext) {
2 var action = filterContext.Result as ViewResult;
3 //Verify that nothing has been previously set. This give the possibility to
4 //still be able to set the master page at a more atomic position (action).
5 if (action != null && String.IsNullOrEmpty(action.MasterName)) {
6 action.MasterName = "MasterPageCustom";
7 }
9 //Default stuff
10 base.OnActionExecuted(filterContext); }

The later solution is the best one in the case that you have multiple action methods that use the same master page. It also give the flexibility to change it for specific action. The first solution should be used if the master page is used for few actions only.