Creating nested master pages

If you are a really heavy user of master pages, then the odds are that you have reached the extent of their usefulness in a single master page environment. This is where having nested master pages may come in to help you. Nested master pages are specifically useful when you want to have a generic master page to specify the site's header, standard navigation, and footer. Then you can have a nested master page to control the specific area of your application. An example of this would be a nested master page for forums, blogs, product catalog, and so on.

How to do it...

  1. Let's start by creating a new MVC application.
  2. Then we will add a new nested master page file called NestedMasterPage1.master (you could just as easily add a view master page—both will work).
  3. Part of creating a new nested master page is picking the master page you want to use for your nested master page—choose the default Site.Master.
  4. Once the nested master page is created, you will see that the two content areas are implemented in the Site.Master. In order for any views to be able to use our nested master page, we need to create some instances of ContentPlaceHolder inside some of the defined content areas.

    Views/Shared/NestedMasterPage1.master:

    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <asp:ContentPlaceHolder ID="TitleContent" runat="server">
    </asp:ContentPlaceHolder>
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    Content provided by the nested master page...
    <asp:ContentPlaceHolder ID="MainContent" runat="server">
    </asp:ContentPlaceHolder>
    </asp:Content>
    
  5. Now we can swap out the master page that our home page uses.

    Views/Home/Index.aspx:

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/NestedMasterPage1.Master" Inherits="System.Web.Mvc.ViewPage" %>
    
  6. The application is now ready to run. You should see the customer message as well as the normal page on the home page.

How it works...

This recipe is similar to the nested master page days of standard ASP.NET web forms. The one nice improvement is that you have some added wizard support for picking the master page that it plans to extend. The basic idea behind how this works is that when a view is loaded, its master page (nested in this case) is loaded, and if there is another master page to load,

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

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