asp.net中主版頁面使用總結

來源:互聯網
上載者:User

asp.net中主版頁面使用總結
一、內容頁訪問主版頁面的方法;
有兩種方法:
1、使用FindControl訪問主版頁面中的控制項
如:Label1.Text = ((Label)Master.FindControl("label1")).Text;

2、使用MasterType指令訪問主版頁面中的控制項
如:Label2.Text = Master.LabelText;

說明:在內容頁中使用MasterType指令後,將使得內容頁中的Master屬性被強型別化,也就是說,通過MasterType指令,可以建立與內容頁相關的主版頁面的強型別引用。由此,可以在內容頁中,使用Master對象訪問主版頁面的公用方法、屬性和控制項等成員。
二、內容頁中動態更改主版頁面;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.MasterPageFile = "~/other.Master";
        }
這種方法要求更換的主版頁面和被更換的主版頁面有相同的ContentPlaceHolder控制項數量和ID。
三、內容頁中動態設定Title
有兩種方法:
1、在Page中設定
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Mainsite.WebForm1" MasterPageFile="~/topbottom.Master" Title="New Web1"%>

2、代碼中設定
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Header.Title = "New Title";
        }
Page.Header屬性返回的是IPageHeader介面類型的執行個體,裡麵包含了Title和StyleSheet。
四、內容頁如何使用css和javascript;
有兩種方法:
1、在內容頁的PageLoad事件中通過代碼來指定本內容頁的css檔案
        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlLink link = new HtmlLink();
            link.Href = "css/projectPage.css";
            link.Attributes["rel"] = "stylesheet";
            link.Attributes["type"] = "text/css";
            this.Header.Controls.Add(link);
        }
2、 在主版頁面的<head></head>中添加一個內容控制項,然後在內容頁中在對應的內容控制項中寫css和javascript代碼。
這種方法和其他Content的用法一樣,就不再多介紹了。

這兩種方法都存在的缺點是:在設計時看不到CSS的效果。

五、內容頁中調用Load中的方法
兩種方法可以實現

1.用戶端:
在內容頁的Content中添加JS代碼。
<script language="javascript" type="text/javascript">

window.onload=function getTime()
{
    var date = new Date(); //日期對象
    var now = "";
    now = date.getFullYear()+"-"; //讀英文就行了
    now = now + (date.getMonth()+1)+"-"; //取月的時候取的是當前月-1如果想取當前月+1就可以了
    now = now + date.getDate();
    document.getElementById("txtAddDate").value=now;
}
</script>

2.伺服器端:

protected override void Render(HtmlTextWriter writer)
     {
         //繼承模板頁的內容頁加入 onload 事件
         System.IO.StringWriter sw = new System.IO.StringWriter();
         HtmlTextWriter htw = new HtmlTextWriter(sw);
         base.Render(htw);
         writer.Write(sw.ToString().Replace("<body", "<body onload=javascript:alert('歡迎光臨!');"));
     }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.