动态加载母版页

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Dynamic1.master.cs" Inherits="WebApplication1.Dynamic1" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    asp:ContentPlaceHolder>
    <style type ="text/css" >
    html
    {
        background :silver;
    }
    
    .content
    {
        background-color:White ;
        height:200px;
    }
        
    style>
head>
<body>
    <form id="form1" runat="server">
    <div class ="content">
        <h1 >Dynamic1h1>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        
        asp:ContentPlaceHolder>
    div>
    form>
body>
html>
View Code

 

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Dynamic2.Master.cs" Inherits="WebApplication1.Dynamic2" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    asp:ContentPlaceHolder>
    <style type ="text/css" >
    html
    {
        background :silver;
    }
    
    .content
    {
        background-color:gray ;
        height:200px;
    }
        
    style>
head>
<body>
    <form id="form1" runat="server">
    <div class ="content">
        <h1 >Dynamic2h1>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        
        asp:ContentPlaceHolder>
    div>
    form>
body>
html>
View Code

 

内容页

<%@ Page Title="" Language="C#" MasterPageFile="~/Dynamic1.Master" AutoEventWireup="true" CodeBehind="DynamicContent.aspx.cs" Inherits="WebApplication1.DynamicContent" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    
        select a master
        <a href ="DynamicContent.aspx?master=Dynamic1">Dynamic1a>
        <a href ="DynamicContent.aspx?master=Dynamic2">Dynamic2a>
       
asp:Content>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class DynamicContent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (Request["master"] != null)
            {
                Page.MasterPageFile = "~/" + Request["master"] + ".Master";
            }
        }
    }
}
View Code

由于在页面的生命周期中第一个要进行的就是母版页和内容页的合并,因此不能再Page_Load事件中加载模板页面,要在Page_PreInit事件进行,这是页面生命周期的首个事件。

你可能感兴趣的:(动态加载母版页)