Controlling which master page is used with a view base class

In this recipe, we are going to take a look at another approach for setting which master page is used by the view. Specifically, we are going to create a base class that can be inherited by our view pages. In the base class we can then override the OnPreInit method, inside of which we can easily control the master page that is used by the view.

How to do it...

  1. Start by creating a new MVC project.
  2. Next, create a copy of the existing master page and call it Site2.Master.
  3. Change the H1 text to show Master 1 and Master 2, so that we can easily tell which master page is being used.
  4. Then we need to create a new class in our Models folder called BaseViewPage.cs.
  5. In the new base class that we are creating, we need to inherit from System.Web.Mvc.Viewpage. Then we need to define a method that overrides the framework's OnPreInit method. Inside of our method, we will build up some logic to check if we are in an even or odd second when the page loads. Based on the result of our test, we will load the Site2.master file or Site.master file.

    Models/BaseViewPage.cs:

    public class BaseViewPage : System.Web.Mvc.ViewPage
    {
    protected override void OnPreInit(EventArgs e)
    {
    if(DateTime.Now.Second%2==0)
    Page.MasterPageFile = "~/Views/Shared/Site2.Master";
    else
    Page.MasterPageFile = "~/Views/Shared/Site.Master";
    base.OnPreInit(e);
    }
    }
    
  6. For this logic to get executed, we need to set our Index view to inherit from our new base class instead of inheriting from System.Web.Mvc.ViewPage.

    Views/Home/Index.aspx:

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MvcApplication1.Models.BaseViewPage" %>
    ...
    
  7. Now you can run your application. Refreshing the home page should show the master pages being switched now and then, based on the second that the page is being loaded.

How it works...

Because our view was set to inherit from our custom base class and our base class catches the OnPreInit event, we are able to set the master page prior to the page being built. This is important as you can toggle the master page that a view uses after it has started being rendered! Now all we need to do is use our base class for all of our views (a good idea even if you don't yet need it, as it will provide you with an added point of extensibility).

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

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