.net深刻體驗與實戰精要--ASP.NET開發大雜燴(轉)

  轉自:http://www.cnblogs.com/sunhan/p/3371337.htmljavascript

正巧今天遇到一個獲取動態生成table中的一個動態生成的TextBox的值的時候老是findcontrol不到。後來通過咱們的徐總,瞬間解決,可是我以爲對於一個頁面的聲明週期,我瞭解的仍是不多,今天但願能經過這篇文章,再次瞭解一遍。html

3.1頁面生命週期

3.1.1獨立頁面生命週期事件順序

複製代碼
 public partial class _Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Response.Write("Page_PreInit<br/>");
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            Response.Write("Page_Init<br/>");

        }
        protected void Page_InitComplete(object sender, EventArgs e)
        {
            Response.Write("Page_InitComplete<br/>");

        }
        protected void Page_PreLoad(object sender, EventArgs e)
        {
            Response.Write("Page_PreLoad<br/>");

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("Page_Load<br/>");

        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            Response.Write("Page_LoadComplete<br/>");

        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            Response.Write("Page_PreRender<br/>");

        }
        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            Response.Write("Page_PreRenderComplete<br/>");

        }
        protected void Page_SaveStateComplete(object sender, EventArgs e)
        {
            Response.Write("Page_SaveStateComplete<br/>");

        }
        protected void Page_Unload(object sender, EventArgs e)
        {
            //Response.Write("Page_Unload<br/>");
            int i = 0;
            i++;//這行代碼是用來設置斷點的,這裏不能用Response.Write
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write("Button事件觸發!<br/>");
        }
    }
複製代碼

輸出結果:java

複製代碼
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Page_SaveStateComplete
複製代碼

這就是獨立頁面的執行順序,但我點擊Button按鈕的時候頁面會進行Postback並從新加載頁面,這個過程事件順序:web

複製代碼
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Button事件觸發!
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Page_SaveStateComplete
複製代碼

這部分雖然很簡單,可是在咱們獲取頁面控件或者相關值的時候,經常找不到控件,很大一部分緣由是由於沒有了解頁面的生命週期事件順序sql

3.1.2具備Master頁的聲明週期事件順序

當頁面有Master頁的時候,將上面代碼分別複製到Site.Matster和ContentPage.aspx,再次執行ContentPage.aspx會看到以下結果:數據庫

複製代碼
Page_PreInit
MasterPage_Init Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
MasterPage_Load Page_LoadComplete
Page_PreRender
MasterPage_PreRender Page_PreRenderComplete
Page_SaveStateComplete
複製代碼

當點擊按鈕的時候編程

複製代碼
Page_PreInit
MasterPage_Init
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
MasterPage_Load
Button事件觸發!
Page_LoadComplete
Page_PreRender
MasterPage_PreRender
Page_PreRenderComplete
Page_SaveStateComplete
複製代碼

3.1.3APS.NET聲明週期詳解跨域

網頁事件瀏覽器

典型的使用方式安全

PreInit

PreInit事件是網頁生命週期中很是早起的一個事件,在PreInit事件觸發以後,就會加載用戶設置信息與網頁主題。咱們一般使用PreInit事件來執行下列處理:

l         檢查IsPostBack屬性,來確認網頁是否爲第一次被處理。

l         建立或從新建立動態控件。

l         動態設置一個母版頁。

l         動態設置Theme屬性。

l         讀取或設置用戶設置文件屬性值。

Init

在全部的控件都已經被初始化,並且全部的面板設置都已經應用以後,就會觸發Init事件。可使用此事件來讀取或初始化控件屬性。

InitComplete

此事件由Page對象觸發。當網頁初始化完成以後,就會觸發此事件。

PreLoad

若是但願在Load事件觸發以前,針對您的網頁或控件執行一些處理,就可使用此事件。在Page觸發此事件以後,它會加載它自己與全部控件的視圖狀態,而後處理Request實例的回發數據。

Load

Page會調用Page上的Load事件處理例程,而後按照順序爲每個子控件執行相同的操做,直到網頁與全部控件被加載爲止。咱們一般會使用Load事件來設置控件的屬性並建立數據庫鏈接。

控件事件

咱們一般使用控件的各個事件來完成各項互動操做。

LoadComplete

在網頁上的全部其餘控件都已經被加載以後,要執行的處理就能夠經過此事件來完成。

PreRender

在控件已經被加載可是尚未解釋以前,就會觸發此事件。在此事件以前會執行下列操做:

l         Page對象會調用網頁與每個控件的EnsureChildControls方法。

l         DataSourceID屬性被設置的數據綁定控件會調用其DataBind方法。

網頁上的每個控件都會觸發PreRender事件,您能夠利用它對網頁或其控件的內容作最後的更改。

SavaStateComplete

在已經爲網頁和網頁上的全部控件保存了視圖狀態與控制狀態信息後,就會觸發此事件。此時對網頁與控件所做的任何更改都會被忽略。

若是您的操做是要在視圖狀態被保存以後才執行,則很是適合使用SaveStateComplete事件,可是請不要對控件進行任何更改。

Render

Render不是一個事件,而是一個方法。在此階段,Page對象會調用每個控件的Render方法。全部的ASP.NET服務器控件都擁有一個Render方法,它會輸出要傳送給瀏覽器的控件標記。當咱們建立一個自定義控件時,一般會重寫Render方法來輸出控件的標記。然而,若是您的自定義控件僅僅是標準的ASP.NET服務器控件,而沒有任何的自定義標記,則不須要重寫Render方法。

Unload

每個控件的Unload事件被觸發以後,纔會觸發網頁的Unload事件。對於控件而言,咱們會使用此事件爲特定的控件進行最後的清理工做,比方說,關閉某控件所使用的數據庫鏈接。

對於網頁自己而言,一樣會使用此事件來進行最後的清理工做,比方說,關閉已打開的文件與數據庫鏈接、完成記錄寫入操做等。

3.2頁面狀態管理

3.2.1 Cookie

1.建立

複製代碼
HttpCookie cookie=new HttpCookie("user");

cookie.Value="sunhan"//賦值只能經過字符串

cookie["sex"]="";  //多個cookie賦值,或者:
cookie.Values.Add("age","20");

cookie.Expires=DateTime.Now.AddHours(1);//控制有效期,從當前時間以後的一個小時

//將Cookie添加到內部的Cookie集合。Cookie集合中全部Cookie均經過Http輸出流在set—Cookie頭中發送到客戶端
Response.AppendCookie(cookie);
//Reponse.Cookie.Add(cookie);
複製代碼

2.讀取

複製代碼
HttpCookie cookie=Request.Cookies["user"];
if(null==cookie)
{
    Response.Write("木有")
}
else
{
    Response.Write("cookie的所有值是:"+cookie.Value+"<br>");
    Response.Write("sex值是:"+cookie["sex"]+"<br>");
    Response.Write("age值是:"+cookie.Values["age"]+"<br>");
}
複製代碼

刪除Cookie

cookie.Expires=DateTime.Now.AddHours(-1);

跨域讀取Cookie

3.2.2 HtmlInputHidden隱藏域

要使用隱藏域,就必須使用Http-Post方法提交互聯網網頁,儘管其名字是隱藏域,但他的值並非隱藏的,咱們能夠經過查看源代碼進行查看。

3.2.3 ViewState

例如:

複製代碼
protected void Page_Load(object sender,EventArgs e)
{
     if (ViewState["arrList"]!=null)
     {
         PageArrayList=(ArrayList)ViewState["arrList"];//從viewstate中獲取數據
     }
     else
     {
        PageArrayList=CreateArray();
     }
     this.GridView1.DataSoure=arrayList;
     this.GridView.DataBind();
}
複製代碼

保存:

protected void Page_PreRender(object sender, EventArgs e )
{
    //能夠在頁面呈現以前保存或更改ViewState數據
    ViewState.Add("arrList",PageArrayList);
}

注意點:

  • 與隱藏域不一樣的是,在使用查看源代碼功能是,ViewState屬性的值是不可見,他被壓縮和加密的。
  • ViewState存在客戶端,減輕服務器段壓力
  • ViewState智能保存可序列化的對象
  • ViewState不適宜存儲大量信息,會加劇服務器解析負擔
  • ViewState安全性低。
  • 能夠關閉ViewState:EnableViewState="false".提升性能。

3.2.4 Request

3.2.5 Aplication對象

若是沒有使用程序強制釋放,則Application對象存在於整個引用程序的生命週期內

Application對象本質上就是一個Hash表,按鍵值存放了對象,因爲對象時全局而且存在在服務器上,並且存在多線程同事訪問,Application裏面存在應該是訪問較多,就該較少而且是全局,至少大部分功能會使用的數據,如計數器,或者數據庫鏈接串等。

3.2.6 Session對象

1.Web.Config文件中的Session配置

複製代碼
< sessionState mode="Off|InProc|StateServer|SQLServer" 
              cookieless="true|false" 
              timeout="number of minutes" 
              stateConnectionString="tcpip=server:port" 
              sqlConnectionString="sql connection string" 
              stateNetworkTimeout="number of seconds" 
/>
複製代碼

必備屬性:

  • mode 設置將Session信息存儲到哪裏
  • Off 設置爲不使用Session功能
  • InProc 設置爲將Session存儲在進程內,就是ASP中的存儲方式,這是默認值。
  • StateServer 設置爲將Session存儲在獨立的狀態服務中。
  • SQLServer 設置將Session存儲在SQL Server中。

可選的屬性是:

  • cookieless 設置客戶端的Session信息存儲到哪裏
  • ture 使用Cookieless模式
  • false 使用Cookie模式,這是默認值。
  • timeout 設置通過多少分鐘後服務器自動放棄Session信息。默認爲20分鐘  stateConnectionString 設置將Session信息存儲在狀態服務中時使用的服務器名稱和端口號

2.Session具體操做

複製代碼
//存儲
Session["myname"]="Mike";
//獲取信息
myname=Session["myname"];

Session.Clear();//從session狀態集合中移除全部鍵和值
Session.Abandon();//取消當前session回話
複製代碼

3.Session超時和莫名丟失處理

緣由:

  • 改動global.asax、Web.config、bin目錄裏的東西,致使Web Application重啓。
  • 有些殺毒軟件會掃描你的WebConfig。
  • 服務器內存不足
  • 程序內部讓session丟失代碼
  • 程序有框架頁面和跨域狀況

解決方法:

  • 修改Web.config中timeout的時效事件
  • 建議讓網上使用獨立的引用程序池
  • ISS設置Session超時事件。網站屬性->主目錄->配置->應用程序池->響應
  • 在應用程序池上打開網站對應的應用程序池將web數量改成1,重啓iss
  • 在如頁面裏嵌入一個iframe,設置寬度和高度爲0,在裏面加載頁面的<head>裏面加入<meta http-equiv="refresh" content="1080">就是定時請求。

4.Session變量和Cookie區別

存儲位置不一樣,保存時間也不一樣

3.3服務器和客戶端數據交互

3.3.1頁面數據綁定全攻略

1.在頁面顯示CS後臺代碼的字符串變量<%=%>、<%#%>

複製代碼
        <div>
            <p>
                姓名:<%= name %>
            </p>
            <p>
                性別:<%= sex %>
            </p>
            <p>
                年齡:<%# old %>
            </p>
        </div>
        <a href="<%=url%>/test.aspx">進入</a>
複製代碼
複製代碼
public partial class WebForm1 : System.Web.UI.Page
    {
        public string name = "ltp";
        public string sex = "man";
        public string old = "25";
        public string url = ConfigurationSettings.AppSettings["Url"];
        protected void Page_Load(object sender, EventArgs e)
        {
            //Page.DataBind(); //千萬不能忘! <%# %>只有DataBind()後纔有效
        }
    }
複製代碼

若是Page.DataBing()被註銷掉,則年齡不會顯示。

二者區別:<%#%>專門用於數據綁定。

2.動態綁定服務器空間屬性值

複製代碼
public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.DataBind();
        }
    }
複製代碼
複製代碼
<form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
                <asp:ListItem Value="images\1.jpg" Selected="True">圖1</asp:ListItem>
                <asp:ListItem Value="images\2.jpg">圖2</asp:ListItem>
                <asp:ListItem Value="images\3.jpg">圖3</asp:ListItem>
            </asp:DropDownList><br />
            <asp:Image ID="Image1" runat="server"
                ImageUrl="<%# DropDownList1.SelectedItem.Value %>"></asp:Image>
        </div>
    </form>
複製代碼

我本想把Page.DataBind()註銷掉的。可是後來想到前臺有<%#%>

 

3.綁定HashTable到DataList

複製代碼
<asp:DataList ID="DataList1" runat="server">
        <HeaderTemplate>
            <table width="200">
                <tr>
                    <td width="100">
                        ENGLISH
                    </td>
                    <td>
                        中文
                    </td>
                </tr>
            </table>
        </HeaderTemplate>
        <ItemTemplate>
            <table width="200">
                <tr>
                    <td width="100">
                        <%# ((DictionaryEntry)Container.DataItem).Key %>
                    </td>
                    <td>
                        <%# ((DictionaryEntry)Container.DataItem).Value %>
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>
複製代碼
複製代碼
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Hashtable list = new Hashtable();
            list.Add("ltp", "李天平");
            list.Add("zs", "張三");
            list.Add("ls", "李四");
            this.DataList1.DataSource = list;
            this.DataList1.DataBind();
        }

    }
複製代碼

4.頁面綁定使用服務器方法

 <%# GetSumCount(1,int.Parse(((DictionaryEntry)Container.DataItem).Key.ToString()))%>

後臺有這個方法。

5.將DataView綁定到DataList,並調用服務器方法。

6.使用DataBinder類進行綁定

7.綁定格式化輸出

8.直接綁定執行javascript方法

複製代碼
    <script language="javascript">
        function DeleteForum(id) {
            if (confirm('你確認要刪除這個論壇及它下面全部的主題嗎?')) {
                document.forms['Forums'].elements['paramID'].value = id;
                __doPostBack('DeleteForum', '');
            }
        }

        function DeleteCategory(id) {
            if (confirm('你確認要刪除這個類別和它的子論壇嗎?')) {
                document.forms['Forums'].elements['paramID'].value = id;
                __doPostBack('DeleteCategory', '');
            }
        }
    </script>
    <form id="form1" runat="server">
        <div>
            <a href='<%# string.Format("javascript:DeleteCategory({0});",
        DataBinder.Eval(Container.DataItem, "CategoryID")) %>'>刪除</a>
            <asp:HyperLink ID="HyperLink1" runat="server"
                NavigateUrl='<%# "javascript:DeleteForum(" + DataBinder.Eval(Container.DataItem, "ForumID") + ")" %>'
                Visible='<%# CanAdministerCategories %>' Text="刪除" />
        </div>
    </form>
複製代碼

3.4 ASP.NET編程中的技巧

3.4.1頁面之間傳值的7種方法。

1.get方法--也就是Request[""];

2.使用內存變量Session和Application

注:Application實質上市整個虛擬目錄中全部文件的集合,若是想在整個應用範圍內使用某個變量值,則Application對象時最佳選擇。

3.Post方法

沒有runat=server

    <form id="form1" action="WebFormC2.aspx" method="post">
        <input name="txtname" type="text" value="litianping" />
        <input type="submit" value="提交到WebFormC2.aspx" />
    </form>
if (Request.Form["txtname"] != null)
            {
                TextBox1.Text = Request.Form["txtname"];
                //TextBox1.Text = Request.Form["SourceData"];
            }

這是有runat=server

複製代碼
    <form id="Form1" method="post" runat="server">
        <input id="btnTransfer" type="button" onclick="post();" runat="server" value="提交到WebFormC2.aspx">
    </form>
    <form id="forPost" method="post">
        <input type="text" runat="server" id="txtname" value="litianping">
    </form>

    <script language="javascript">
        function post() {
            forPost.action = "WebFormC2.aspx";
            forPost.submit();
        }
    </script>
複製代碼

4.靜態變量

複製代碼
//fasong
//定義一個公共變量
        public static string str = "";
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            str = this.TextBox1.Text;
            Server.Transfer("WebFormD2.aspx");
        }
//jieshou
protected void Page_Load(object sender, EventArgs e)
        {
            this.TextBox1.Text = WebFormD1.str;
        }
複製代碼

5.Context.Handler獲取控件

            <asp:TextBox ID="TextBox1" Text="litianping" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="進入WebFormE2.aspx"
                OnClick="Button1_Click" />       // 後臺事件       //Server.Tansfer("WebFormE2.aspx");

接受頁

複製代碼
protected void Page_Load(object sender, EventArgs e)
        {
            //獲取post過來的頁面對象
            if (Context.Handler is WebFormE1)
            {
                //取得頁面對象
                WebFormE1 poster = (WebFormE1)Context.Handler;

                //取得控件                
                this.TextBox1.Text = ((TextBox)poster.FindControl("TextBox1")).Text;
                //this.TextBox1.Text = poster.TextBox1.Text;
            }
        }
複製代碼

6.Context.Items變量

發送:

        protected void Button1_Click(object sender, EventArgs e)
        {
            Context.Items["name"] = TextBox1.Text;
            Server.Transfer("WebFormG2.aspx");
        }
複製代碼
//接收 protected void Page_Load(object sender, EventArgs e)
        {
            //獲取post過來的頁面對象
            if (Context.Handler is WebFormG1)
            {
                this.TextBox1.Text = Context.Items["name"].ToString();

            }
        }
複製代碼

3.4.4 Server.Transfer和Response.Redirect的區別

Server.Transfer沒有離開服務器,request,session等內部控件保存的信息不變。

Response.Redirect發送一個HTTP響應到客戶端瀏覽器,要進行頁面跳轉。

3.4.5 刷新頁面彙總

1.實現頁面自動刷新

<meta http-equiv="refesh" content="5">

每隔5秒刷新一次

2.頁面自動跳轉

<meta http-equiv="refesh" content="5";url=www.baidu.com>

3.setTimeout實現

<body onload="setTimeout('history.go(0)',5000)">

<body onload="setTimeout('this.location.reload();',5000)">

按鈕刷新的n中方法

複製代碼
<input type=button value="刷新" onclick="history.go()">
<input type=button value="刷新" onclick="locaction.reload()">
<input type=button value="刷新" onclick="location=location">
<input type=button value="刷新" onclick="location.assign(location)">
<input type=button value="刷新" onclick="document.execCommand('Refresh')">
<input type=button value="刷新" onclick="window.navigate(lacation)">
<input type=button value="刷新" onclick="location.replace(location)">
<input type=button value="刷新" onclick="history.go()">
<input type=button value="刷新" onclick="window.open
('www.baidu.com','_self')">
<input type=button value="刷新" onclick="document.all.WebBrowser.ExecWB(22,1)">
複製代碼
相關文章
相關標籤/搜索