说道ASP.NET Postback,就得说Web Page生命周期,但是Web Page生命周期却不是三言两语就能够说得清楚的,所以在这里单纯站的编程的角度,撇开Web Page生命周期浅谈Postback。
我们知道,无论是ASP.NET1.x,2.0,甚至是以后的版本,ASP.NET最终Render到Client端通过浏览器浏览的都是一样:一个单纯的HTML。Client通过Submit Form的方式将填入Form的数据提交给Server进行处理。我们现在来看看ASP.NET Postback程序处理的过程。
首先我们通过一个Sample来看ASP.NET如何处理一个通过Click一个Button引起的Postback。下面是Web Page的HTML:
- <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.
aspx.cs"Inherits="_Default"%>- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">- <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunatheadrunat="server">
- <title>TestPage</title>
- </head>
- <body>
- <formidformid="form1"runat="server">
- <div>
- <asp:Labelrunatasp:Labelrunat="server"ID="LabelMessage"ForeColor="red"></asp:Label>
- </div>
- <div>
- <asp:Buttonrunatasp:Buttonrunat="server"ID="Button1"Text="Button1"OnClick=
"Button1_Click"OnCommand="Button_Command"CommandArgument="Button1"/>- <asp:Buttonrunatasp:Buttonrunat="server"ID="Button2"Text="Button2"OnClick=
"Button2_Click"OnCommand="Button_Command"CommandArgument="Button2"UseSubmitBehavior="false"/>- <asp:Buttonrunatasp:Buttonrunat="server"ID="Button3"Text="Button3"OnClick=
"Button3_Click"OnCommand="Button_Command"CommandArgument="Button3"UseSubmitBehavior="false"/>- </div>
- </form>
- </body>
- </html>
很简单,定义了3个Button,分别注册了他们的两个Event:Click和Command。3个Button的Command Event Hander是一样的:Button_Command,通过指定的CommandArgument来让Event Handler判断到底是哪个Button触发了Command Event。
下面是Code Behind:
- usingSystem;
- usingSystem.Data;
- usingSystem.Configuration;
- usingSystem.Web;
- usingSystem.Web.Security;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- usingSystem.Web.UI.WebControls.WebParts;
- usingSystem.Web.UI.HtmlControls;
- publicpartialclass_Default:System.Web.UI.Page
- {
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- }
- protectedvoidButton1_Click(objectsender,EventArgse)
- {
- stringstringmessage=string.Format("The{0}eventof{1}isfired","Click","Button1");
- this.LabelMessage.Text=message;
- }
- protectedvoidButton2_Click(objectsender,EventArgse)
- {
- stringstringmessage=string.Format("The{0}eventof{1}isfired","Click","Button2");
- this.LabelMessage.Text=message;
- }
- protectedvoidButton3_Click(objectsender,EventArgse)
- {
- stringstringmessage=string.Format("The{0}eventof{1}isfired","Click","Button3");
- this.LabelMessage.Text=message;
- }
- protectedvoidButton_Command(objectsender,CommandEventArgse)
- {
- stringstringmessage=string.Format("The{0}eventof{1}isfired",
"Command",e.CommandArgument);- this.LabelMessage.Text+=";"+message;
- }
- }
以上介绍ASP.NET Postback的Web Page生命周期.
【编辑推荐】