Introduction to ASP. NET Postback

Source: Internet
Author: User

 

ASP. NET Postback, you have to talk about the lifecycle of the Web Page, but the lifecycle of the Web Page can be clearly stated in a few words. Therefore, from the perspective of station programming, talk about Postback Based on the Web Page lifecycle.

We know that no matter ASP. NET1.x, 2.0, or even later versions, ASP. NET will eventually Render to the Client side and browse through a browser: A simple HTML. The Client submits the data filled in Form to the Server for processing by Submit Form. Now let's take a look at the process of processing ASP. NET's entire Postback program.

 

First, let's use a Sample to see how ASP. NET handles a Postback caused by clicking a Button. The following is the HTML of the Web Page:

 

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>

<! 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> Test Page </title>

</Head>

<Body>

<Form id = "form1" runat = "server">

<Div>

<Asp: Label runat = "server" ID = "LabelMessage" ForeColor = "red"> </asp: Label>

</Div>

<Div>

<Asp: Button runat = "server" ID = "Button1" Text = "Button1" OnClick = "button#click" OnCommand = "Button_Command" CommandArgument = "Button1"/>

<Asp: button runat = "server" ID = "Button2" Text = "Button2" OnClick = "Button2_Click" OnCommand = "Button_Command" CommandArgument = "Button2" UseSubmitBehavior = "false"/>

<Asp: button runat = "server" ID = "Button3" Text = "Button3" OnClick = "Button3_Click" OnCommand = "Button_Command" CommandArgument = "Button3" UseSubmitBehavior = "false"/>

</Div>

</Form>

</Body>

</Html>

 

It is easy to define three buttons and register their two events: Click and Command. The Command Event Hander of the three buttons is the same: Button_Command. The specified CommandArgument allows the Event Handler to determine which Button triggers the Command Event.

 

The following is Code Behind:

 

Using System;

Using System. Data;

Using System. Configuration;

Using System. Web;

Using System. Web. Security;

Using System. Web. UI;

Using System. Web. UI. WebControls;

Using System. Web. UI. WebControls. WebParts;

Using System. Web. UI. HtmlControls;

 

Public partial class _ Default: System. Web. UI. Page

{

 

Protected void Page_Load (object sender, EventArgs e)

{

}

Protected void button#click (object sender, EventArgs e)

{

String message = string. Format ("The {0} event of {1} is fired", "Click", "Button1 ");

This. LabelMessage. Text = message;

}

Protected void Button2_Click (object sender, EventArgs e)

{

String message = string. Format ("The {0} event of {1} is fired", "Click", "Button2 ");

This. LabelMessage. Text = message;

}

Protected void Button3_Click (object sender, EventArgs e)

{

String message = string. Format ("The {0} event of {1} is fired", "Click", "Button3 ");

This. LabelMessage. Text = message;

}

 

Protected void Button_Command (object sender, CommandEventArgs e)

{

String message = string. Format ("The {0} event of {1} is fired", "Command", e. CommandArgument );

This. LabelMessage. Text + = ";" + message;

}

}

 

Run the Page and Click a button (such as Button2 ):

 

 

We can see from the top Message that the Click Event and Command of Button2 are triggered successively.

 

The main purpose of this Blog is to describe the entire program running process from the perspective of method calling: From the HTML being Render to the Client side, to the user clicking a button, the input is Postback to the Server side, trigger two events and execute Event Handler to print the related Message.

 

First, let's take a look at what Page Render-to-Client HTML designed by ASP. NET looks like:

 

<! 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>

<Title>

Test Page

</Title>

</Head>

<Body>

<Form name = "form1" method = "post" action = "Default. aspx" id = "form1">

<Div>

<Input type = "hidden" name = "_ EVENTTARGET" id = "_ EVENTTARGET" value = ""/>

<Input type = "hidden" name = "_ EVENTARGUMENT" id = "_ EVENTARGUMENT" value = ""/>

<Input type = "hidden" name = "_ VIEWSTATE" id = "_ VIEWSTATE" value = "/wEPDwUKMTA0NDQ2OTE5OWRk281L4eAk7iZT10hzg + BeOyoUWBQ ="/>

</Div>

 

<Script type = "text/javascript">

<! --

Var theForm = document. forms ['form1'];

If (! TheForm ){

TheForm = document. form1;

}

Function _ doPostBack (eventTarget, eventArgument ){

If (! TheForm. onsubmit | (theForm. onsubmit ()! = False )){

TheForm. _ EVENTTARGET. value = eventTarget;

TheForm. _ EVENTARGUMENT. value = eventArgument;

TheForm. submit ();

}

}

// -->

</Script>

 

<Div>

<Span id = "LabelMessage" style = "color: Red;"> </span>

</Div>

<Div>

<Input type = "submit" name = "Button1" value = "Button1" id = "Button1"/>

<Input type = "button" name = "Button2" value = "Button2" onclick = "javascript :__ doPostBack ('button2','') "id =" Button2 "/>

<Input type = "button" name = "Button3" value = "Button3" onclick = "javascript :__ doPostBack ('button3','') "id =" Button3 "/>

</Div>

</Form>

</Body>

</Html>

 

The above HTMLBody consists of three parts:

 

1. Three hidden fields are defined:

 

<Input type = "hidden" name = "_ EVENTTARGET" id = "_ EVENTTARGET" value = ""/>

<Input type = "hidden" name = "_ EVENTARGUMENT" id = "_ EVENTARGUMENT" value = ""/>

<Input type = "hidden" name = "_ VIEWSTATE" id = "_ VIEWSTATE" value = "/wEPDwUKMTA0NDQ2OTE5OWRk281L4eAk7iZT10hzg + BeOyoUWBQ ="/>

 

From their names, we can see what they mean: __eventtarget represents the Unique name of the Control that triggers the Event; __eventargument represents the additional parameter defined for Event Handler; __ VIEWSTATE: viewstate.

 

2. A script:

 

<Script type = "text/javascript">

<! --

Var theForm = document. forms ['form1'];

If (! TheForm ){

TheForm = document. form1;

}

Function _ doPostBack (eventTarget, eventArgument ){

If (! TheForm. onsubmit | (theForm. onsubmit ()! = False )){

TheForm. _ EVENTTARGET. value = eventTarget;

TheForm. _ EVENTARGUMENT. value = eventArgument;

TheForm. submit ();

}

}

// -->

</Script>

 

Defines a _ doPostBack function to complete the Postback operation. This function only has three lines of code. The first two lines assign values to the two hiddden fields defined above through parameters, then, submit the form to the Server.

3. HTML corresponds to Web Control defined through ASP. NET.

 

<Div>

<Span id = "LabelMessage" style = "color: Red;"> </span>

</Div>

<Div>

<Input type = "submit" name = "Button1" value = "Button1" id = "Button1"/>

<Input type = "button" name = "Button2" value = "Button2" onclick = "javascript :__ doPostBack ('button2','') "id =" Button2 "/>

<Input type = "button" name = "Button3" value = "Button3" onclick = "javascript :__ doPostBack ('button3','') "id =" Button3 "/>

Div>

 

 

The three buttons we defined are converted into three <input> tags that can submit forms to the Server, but they submit tables in different ways, the first one is submitted in <input type = "submit"> mode, and the last two are submitted by calling javascript (<input type = "button"> ). For a System. web. UI. webControls. button, which adopts the first submission method by default, but we set the UseSubmitBehavior attribute (ASP. NET 2.0, 1x does not have the corresponding settings), change the form submission behavior.

When you Click Button2, call _ doPostBack and input two parameters: a Unique name representing the object of the Event, that is, the name of Button2, another parameter that describes the extra information of the Event, which is not required here, so it is a null string. In _ doPostBack, assign these two parameters to two Hidden fields :__ EVENTTARGET ,__ EVENTARGUMENT. Then, submit the form to the Server to complete Postback.

 

Then let's take a look at how the Server handles this Postback. We will not detail the Web Page lifecycle here. The Server finds the corresponding Control through the value of the hidden field of _ EVENTTARGET, and determines whether the Control implements the System. Web. UI. IPostBackEventHandler Interface through Reflection. If the Control does implement this Interface, call the RaisePostBackEvent method of Page, which is a Virtual method and can be overwritten. Let's look at the definition of this method.

 

[EditorBrowsable (EditorBrowsableState. Advanced)]

Protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)

{

SourceControl. RaisePostBackEvent (eventArgument );

}

 

We can see that this method directly calls the RaisePostBackEvent of the sourceControl and passes in an eventArgument parameter. In this example, sourceControl is the Web Control: Button2 corresponding to _ EVENTTARGET, eventArgument is the value of _ EVENTTARGET: An empty string. The Button2 type is System. Web. UI. WebControls. Button. Let's take a look at how the RaisePostBackEvent method in System. Web. UI. WebControls. Button is defined:

 

Protected virtual void RaisePostBackEvent (string eventArgument)

{

Base. ValidateEvent (this. UniqueID, eventArgument );

If (this. CausesValidation)

{

This. Page. Validate (this. ValidationGroup );

}

This. OnClick (EventArgs. Empty );

This. OnCommand (new CommandEventArgs (this. CommandName, this. CommandArgument ));

}

 

This method is also very simple. First, verify, and then start two events: OnClick and OnCommand, and then call the corresponding Event handler, which is consistent with our output.

 

This is basically the whole process of executing the Postback program. Now we make some interesting changes to our Page to verify it:

 

Form Submitting is the way for the Client to interact with the Server, but we now have two ways to submit the Form: Through the <input type = "submit"> control; by calling javascript :__ doPostBack. Based on this, we added the following javascript in Html:

 

<Script type = "text/javascript">

Function postback ()

{

_ DoPostBack ('button1 ','');

}

Document. getElementById ("Button2"). onclick = postback;

Document. getElementById ("Button3"). onclick = postback;

</Script>

 

 

The onclick events of override Button2 and Button3 pass 'button1 as the parameter to the _ doPostBack method. As you can imagine, no matter which Button you Click, the program will regard it as Click Button1. If you are interested, try it by yourself. No matter which Button you Click, the display effect will be as follows:

 

Next, we will cancel the above changes and try the Code on the Server. As we mentioned earlier, the Server receives the Client's Postback. For the Web Control (or Html Server Control) of the event, if the System is implemented. web. UI. the IPostBackEventHandler interface will call the virtual method of Page: RaisePostbackEvent. Let's Override this method now:

 

Protected override void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)

{

SourceControl = this. Button1;

Base. RaisePostBackEvent (sourceControl, eventArgument );

}

 

 

In the above Code, we set sourceControl to Button1, so that no matter which Button is clicked on the client side, it will be considered as the Click of the Button. The running result is the same as above.

Through the above introduction, we know that RaisePostBackEvent of Page will call the RaisePostBackEvent method of Source Control. This method is defined in the IPostBackEventHandler interface, and many controls implement this method. For the Button, this method is Virtual and can be Override. If you are interested, you can write a Custom Button and Override the method to check the execution status, I believe this will deepen your understanding of Postback.

Author: Artech

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.