In this recipe, we will take a look at how to control our master pages at a higher level. We will create a controller base class. In the controller base class, we will then take control of which master page is used by the views that are controlled by controllers that inherit from our shiny new base class.
Site2.master
. H1
text for each of the master pages to Master 1
and Master 2
accordingly. BaseController
class in the Models
folder. This class will inherit from Controller
. Then we will set the BaseController
to override the OnActionExecuted
method. In this method, we will get an instance of the current ViewResult
from the passed-in context. We need to check to make sure that the instance is not null. Then we will perform some logic to check if we are in an even or odd second, and set the corresponding master page based on the results of that test. Then we return the context to the pipeline.Models/BaseController.cs:
public class BaseController : Controller { protected override void OnActionExecuted( ActionExecutedContext filterContext) { var action = filterContext.Result as ViewResult; if (action != null) { if (DateTime.Now.Second % 2 == 0) action.MasterName = "Site2"; else action.MasterName = "Site"; } base.OnActionExecuted(filterContext); } }
BaseController
created we can wire it up to our HomeController
by having our HomeController
inherit the new BaseController
.Controllers/HomeController.cs:
public class HomeController : BaseController
This is just another example of a hook that we can attach to affect how the MVC application works. In this case, we are hooking into the OnActionExecuted
event. This event is raised prior to the view being rendered and after the action
method is executed—which means we still have time to alter the master page that is used by the current view.