Event Processing in ASP. NET and ASP. NET

Source: Internet
Author: User

Event Processing in ASP. NET and ASP. NET

I. Events in ASP. NET mainly support three major event groups:
1. include automatically generated when the asp.net page is generated. We use these events to create a page (such as page_load)
2. contains all the events that occur when the user interacts with the page (this is the most powerful)
3. html internal events, which are executed on the browser (mainly implemented by javascript ).

In C #, there are two main methods to process events:
1. Delegate Event Model (the Event Delegate relationship needs to be manually established in VS2003, and VS2005 does not need it .)
2. overload of the Event Method (reload the Method in the control code)

2. Add client events to the ASP. NET Server:

Not all operations on the server control are performed on the server. Some events are executed by the client script, which greatly enhances the availability of the server control. For example, ASP. NET verification control, you can put some work on the client for verification.

The ASP. NET Server Control can send two client scripts:
1. client script block: the client script block is usually written in JavaScript, which usually contains the function executed when a specific client event occurs.
You can use the System. Web. UI. Page class to send the client code to the HTML provided by the ASP. NET Web Page:
(1) RegisterStartupScript (key, script): sends the script block at the end of the Web form (before the </form> mark.
(2) RegisterClientScriptBlock (key, script): sends the script block at the beginning of the Web form (followed by the <form runat = "server"> identifier.
For example:

1 protected override void OnPreRender (EventArgs e)
2 {
3 if (! Page. ClientScript. IsClientScriptBlockRegistered ("Common "))
4 {
5 Page. ClientScript. RegisterClientScriptBlock (typeof (Page), "Common", ClientJavaScriptCodeScipt ("Common. js "));
6}
7 if (! Page. ClientScript. IsClientScriptBlockRegistered (ScriptKey ))
8 {
9 Page. ClientScript. RegisterClientScriptBlock (typeof (Page), ScriptKey, ClientJavaScriptCodeScipt ("DateTime. js "));
10}
11}


2. Client HTML attribute: the client HTML attribute provides a method to link client events with client scripts.
This method is only applicable to server controls exported from the System. Web. UI. WebControls. WebControl class, because the controls exported from this class will send some HTML elements.
The WebControl class contains a method for adding HTML element attributes to HTML elements sent by Web controls. This method is called AddAttributesToRender () and has only one input parameter, that is, the instance of HtmlTextWriter.
Of course, in the current development control, there is no need to add events to HTML elements in this way, especially in the case of AJAX mode, you can use $ addHandler on the client to bind events to HTML elements.

1 /// <summary>
2 // present the control to the specified output parameter.
3 /// </summary>
4 /// <param name = "output"> HTML writer to be written </param>
5 protected override void AddAttributesToRender (HtmlTextWriter output)
6 {
7 output. addattridown ("onmousedown", "setday (this );");
8 output. addattrieric ("onkeypress", "EnsureNumeric (event )");
9
10 base. AddAttributesToRender (output );
11}

The example below illustratesHow to add client events on ASP. NET Server:

1 using System;
2 using System. Data;
3 using System. Configuration;
4 using System. Collections;
5 using System. Web;
6 using System. Web. Security;
7 using System. Web. UI;
8 using System. Web. UI. WebControls;
9 using System. Web. UI. WebControls. WebParts;
10 using System. Web. UI. HtmlControls;
11
12 namespace ServerToClientScript
13 {
14 public partial class _ Default: System. Web. UI. Page
15 {
16 protected void Page_Load (object sender, EventArgs e)
17 {
18 string script = "return confirm ('Are you sure you want to delete it? ');";
19 this. Button1.Attributes. Add ("onclick", script );
20
21 if ((! Page. IsStartupScriptRegistered ("PopUp ")&&(! Page. IsPostBack )))
22 {
23 string scriptBlock = "<script language = 'javascript '> alert ('send client script! '); </Script> ";
24 Page. RegisterStartupScript ("PopUp", scriptBlock );
25}
26}
27}
28}


3. server events are triggered through client events:

In fact, the server events of the server control are simulated by the client's JavaScript. For example, I added a server control DropDownList on the page, set its AutoPostBack to True, and set its SelectedIndexChanged event.
Protected void dropdownlistincluselectedindexchanged (object sender, EventArgs e)
{

}

After running the page, the HTML code is: we can see that the SelectedIndexChanged event on the server is simulated as the onchange event in JavaScript.

1 <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
3 4 5. No title page
6 </title> 7 <body>
8 <form name = "form1" method = "post" action = "MNEvent. aspx" id = "form1">
9 <div>
10 <input type = "hidden" name = "_ EVENTTARGET" id = "_ EVENTTARGET" value = ""/>
11 <input type = "hidden" name = "_ EVENTARGUMENT" id = "_ EVENTARGUMENT" value = ""/>
12 <input type = "hidden" name = "_ LASTFOCUS" id = "_ LASTFOCUS" value = ""/>
13 <input type = "hidden" name = "_ VIEWSTATE" id = "_ VIEWSTATE" value = "/inputs/GyUwiYstw ="/>
14 </div>
15
16 <script type = "text/javascript">
17 <! --
18var theForm = document. forms ['form1 '];
19if (! TheForm ){
20 theForm = document. form1;
21}
22 function _ doPostBack (eventTarget, eventArgument ){
23 if (! TheForm. onsubmit | (theForm. onsubmit ()! = False )){
24 theForm. _ EVENTTARGET. value = eventTarget;
25 theForm. _ EVENTARGUMENT. value = eventArgument;
26 theForm. submit ();
27}
28}
29 // -->
30 </script>
31
32
33 <div>
34 <select name = "DropDownList1" onchange = "javascript: setTimeout ('_ doPostBack (\ 'dropdownlist1 \', \ ')', 0) "id =" DropDownList1 ">
35 <option selected = "selected" value = "male"> male </option>
36 <option value = ""> female </option>
37
38 </select> </div>
39
40 <div>
41
42 <input type = "hidden" name = "_ EVENTVALIDATION" id = "_ EVENTVALIDATION" value = "/wEWBALgifCwDwKd5I/Hangzhou"/>
43 </div> </form>
44 </body>
45 46
47 Since the events of the server control are simulated by the client JavaScript, we can use the client events to trigger server events.
During control development, the control server event is simulated by the client JavaScript (_ doPostBack)

For example, ClientToServerEvent (the attachment contains code)
The onchange client event of DropDownList is used to trigger the server-side event Click Event of the server-side control Button, for example:

1 using System;
2 using System. Data;
3 using System. Configuration;
4 using System. Collections;
5 using System. Web;
6 using System. Web. Security;
7 using System. Web. UI;
8 using System. Web. UI. WebControls;
9 using System. Web. UI. WebControls. WebParts;
10 using System. Web. UI. HtmlControls;
11
12 namespace ServerToClientScript
13 {
14 public partial class ClientToServerEvent: System. Web. UI. Page
15 {
16 protected void Page_Load (object sender, EventArgs e)
17 {
18 string strCMD = Page. GetPostBackClientHyperlink (Button1 ,"");
19 string script = @ "javacrept: ConfirmUpdate (" "EVAL_MESSAGE "");";
20 script = script. Replace ("EVAL_MESSAGE", strCMD );
21 DropDownList1.Attributes. Add ("onchange", script );
22}
23
24 protected void button#click (object sender, EventArgs e)
25 {
26 Response. Write ("I'm from the server, saved! ");
27}
28}
29}
30

Write a JavaScript script on the page:

1 <script type = "text/javascript">
2 function ConfirmUpdate (cmd)
3 {
4 if (confirm ("Do you really want to save it? "))
5 {
6 eval (cmd); // The eval function calls the command contained in a string
7}
8 else
9 {
10 alert ("I'm from the client, canceled! ");
11}
12}
13 </script>

 

In this way, when my DropDownList option changes, the onchange client event is triggered, and then the event triggers the Button server event.

Iv. ASP. NET event model Mechanism

1. ASP. NET is a revolutionary change to the previous ASP, largely because ASP. NET is a new event-driven technology.
2. in ASP. NET, time triggering and processing are performed on the client and server.
3. In ASP. NET, if event information is frequently transmitted with the server, the server's processing efficiency and performance will be greatly reduced. Therefore, some events such as OnMouseOver are not provided;
4. But a Change event is provided. To improve the efficiency, the events are cached on the client and sent back together when the event information is sent to the server again.
Such as the change event in the text box, the change event in the drop-down box,
For example, in the change event of two controls:

1 protected void dropdownlistincluselectedindexchanged (object sender, EventArgs e)
2 {
3 Response. Write ("DropDownList control select change! <Br> ");
4}
5
6 protected void TextBox1_TextChanged (object sender, EventArgs e)
7 {
8 Response. Write ("TextBox text changed! <Br> ");
9}

If the AutoPostBack of the control is set to false (the default value is false ),

The change event is not executed, but the event information is cached on the client,
When you click a server control Button on the page,
Protected void button#click (object sender, System. EventArgs e)
{
Response. Write ("click the Button! <Br> ");
}
At this time, the event information in the client is sent to the server, and all the events are executed, and the information returned to the client is:
TextBox text changed!
DropDownList Control Selection changed!
Click the Button!

For more information about the sample code, see the attachment.
ServerToClientScript.rar


General event processing location in aspnet

If it cannot be found and can be run, it is compiled. The compiled dll file is under the bin directory. You can find the decompiled software for decompilation, generally, you can find the method.

How to bind an event handler to an event in aspnet

Button1.click + = new eventhandler (button#click)
Delegated; delegated is the packaging of methods
Use a delegate when you are unsure of the method to be called and cannot use abstraction or polymorphism.

For example, when a button is clicked, it must trigger the event and perform some processing. If you are a developer of this control, how do you know what to do when a button is clicked? What container will contain your button? Therefore, you must publish an event and use the controls to implement its functions.
 

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.