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.
Site2.Master
. H1
text to show Master 1
and Master 2
, so that we can easily tell which master page is being used. Models
folder called BaseViewPage.cs
. 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); } }
System.Web.Mvc.ViewPage
.Views/Home/Index.aspx:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MvcApplication1.Models.BaseViewPage" %>
...
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).