Setting the master page from a controller base class

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.

How to do it...

  1. The first step is to create a new MVC application.
  2. Then copy the existing master page and create a new master page called Site2.master.
  3. Next, change the H1 text for each of the master pages to Master 1 and Master 2 accordingly.
  4. Now, we can create a 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);
    }
    }
    
  5. With our 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
    
  6. Now you can run the application and refresh the home page. You should see the Site and Site2 master pages being used now and then.

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset