简体   繁体   中英

Nested Master Pages change programmatically

I have a PAGE with a structure like this:

PAGE = MASTER PAGE A + nested MASTER PAGE B of A

MASTER PAGE A:

-----------
Header
-----------
BODY
-----------
Footer
-----------

MASTER PAGE B:

BODY-------------------------------
          |         |             |  
ColumLeft | Content | ColumRight  |
          |         |             |
-----------------------------------

One of the features I need to develop is to be able to change the nested MASTER PAGE programmatically. For example changing MASTER PAGE B with C (containing a different layout like just 2 columns) maintaining the Header and Footer centralized.

At the moment on PAGE I use this code to select another MP, but I am not able to do it because seems when selecting a new nested page asp.net loose the reference to the main MASTER PAGE A.

void Page_PreInit(Object sender, EventArgs e)
{
    this.MasterPageFile = "~/NewMaster.master";
}

Questions:

  • Any idea how to solve it?
  • Would be better have only a Master Page (1 Level) and include the Header and Footer with another tecnic? If yes what would you suggest me?

In this case I wouldn't use nested masterpages, but just one masterpage. For the columns I would use RenderPartial or RenderAction. It's not as DRY as you would wish, because you need to add RenderPartial("LeftColumn") in every view, so I understand your problem, but this is the way I do it.

NB: RenderAction is availbale in MVC. For an article about it see eg: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

In order to change the MasterPage programmatically you have to specify its type right after the page registration link in the xml/html page.

<%@ Page Language="C#" 
    MasterPageFile="~/MasterPage.master" 
    AutoEventWireup="false" 
    CodeFile="MyCodeFile.aspx.cs" 
    Inherits="MyCodeFile"
    title="Untitled Page" %>
<%@ MasterType 
    virtualpath="~/MasterPage.master" 
%>

I don't recommend using this architecture to achieve what you want to achieve, but this is how you would do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM