Asp. NET event handling

Source: Internet
Author: User

First, ASP. NET events primarily support 3 major event groups:
1. Generated automatically when ASP. Build page, we use these events to build pages (such as Page_Load, etc.)
2, contains all the events that occur when the user interacts with the page (this is the most powerful)
3, HTML internal events, these events are executed on the browser (mainly by JavaScript).

In the C # language, there are two main ways to handle events:
1, the delegate-type event processing mode (delegation event model) (VS2003 need to manually establish the event of the delegation relationship, VS2005 no need. )
2. Overloads of the overloaded method (Event method) (overloaded methods in control code)

Second, ASP. NET service side Add client events:

server controls do not all operate on the server side, and some events are performed through client script, which can greatly enhance the usability of the server control. such as the ASP. NET validation control, you can put some work on the client side for validation.

Asp. NET server controls can send two types of client script:
1. Client Script block: Client script blocks are usually written in JavaScript, which typically contains functions that are executed when a particular client event occurs.
The way to send a script block is to use the two methods contained in the System.Web.UI.Page class to send client code to the HTML provided by an ASP. NET Web page:
(1), RegisterStartupScript (Key,script): sends a script block at the end of the Web form (before the </form> tag).
(2), RegisterClientScriptBlock (Key,script): sends a script block at the beginning of the Web form (immediately after <form runat= "Server" > Identity).
Such as:

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 properties: Client HTML properties provide a way to associate client-side events with client-side scripting.
This approach applies only to server controls that are exported from the System.Web.UI.WebControls.WebControl class, because controls that are exported from this class send some HTML elements.
The WebControl class contains a method that adds an HTML element property to an HTML element emitted by a Web control called AddAttributesToRender (), which has only one input parameter, which is an instance of HtmlTextWriter.
Of course, there is no need to add events to HTML elements in this way in the current development control, especially in the case of Ajax mode, where the client can bind events to HTML elements via $addhandler.

1//<summary>
2///renders this control to the specified output parameter.
3//</summary>
4//<param name= "Output" > HTML writer to write to </param>
5 protected override void AddAttributesToRender (HtmlTextWriter output)
6 {
7 output. AddAttribute ("onmousedown", "setday (this);");
8 output. AddAttribute ("onkeypress", "Ensurenumeric (event)");
9
Ten base. AddAttributesToRender (output);
11}

The following example illustrates the ASP. NET service side how to add client events :

1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using system.web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12namespace Servertoclientscript
13{
public partial class _default:system.web.ui.page
15 {
protected void Page_Load (object sender, EventArgs e)
17 {
String script = "return confirm (' Really want to delete it?") ‘);";
this. BUTTON1.ATTRIBUTES.ADD ("onclick", script);
20
if (! Page.isstartupscriptregistered ("PopUp") && (! Page.IsPostBack)))
22 {
String scriptblock = "<script language= ' JavaScript ' >alert (' Send client Script! ');</script> ";
Page.registerstartupscript ("PopUp", Scriptblock);
25}
26}
27}
28}


Third, the server-side event is raised through the client event:

In fact, the server side of the service-side event is simulated by the client's JavaScript, such as I added a DropDownList on the page, and set its autopostback to true, and then set its SelectedIndexChanged Events
protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e)
{

}

After running the page, we find that the HTML code shows that the server-side SelectedIndexChanged event is modeled as a 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
345 Untitled 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= "/ wepdwullte3odi0mjgznjcpzbycagmpzbycagepegrkfgfmzgsyteyi45lmyps34yph/gyuwiystw== "/>
14</div>
15
16<script type= "Text/javascript" >
17<!--
18var theform = document.forms[' Form1 '];
19if (!theform) {
Theform = Document.form1;
21}
22function __doPostBack (Eventtarget, eventargument) {
if (!theform.onsubmit | | (Theform.onsubmit ()! = False)) {
Theform.__eventtarget.value = Eventtarget;
Theform.__eventargument.value = eventargument;
Theform.submit ();
27}
28}
29//--
30</script>
31
32
<div>
<select name= "DropDownList1" onchange= "Javascript:settimeout (' __doPostBack (\ ' dropdownlist1\ ', \ ' \ ') ', 0)" id= " DropDownList1 ">
<option selected= "selected" value= "male" > Male </option>
<option value= "Women" > Women </option>
37
38</select></div>
39
40<div>
41
<input type= "hidden" name= "__eventvalidation" id= "__eventvalidation" value= "/wewbalgifcwdwkd5i/lcgku4aslbglqu Aslbtn23paahgquhpssi0gzsi57eadh "/>
43</div></form>
44</body>
4546
47

Since the events of the server-side control are simulated by the client's JavaScript, we can raise the server event through the client event.
In control development, the server-side event of a control is simulated by the client's JavaScript (__dopostback)

Example Clienttoserverevent (there is code in the attachment)
The server-side event Click event that is raised by the DropDownList OnChange client event to the server control button, such as:

1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using system.web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12namespace Servertoclientscript
13{
public partial class ClientToServerEvent:System.Web.UI.Page
15 {
protected void Page_Load (object sender, EventArgs e)
17 {
String strcmd = Page.getpostbackclienthyperlink (Button1, "");
string script = @ "Javacript:confirmupdate (" "Eval_message" ");";
script = script. Replace ("Eval_message", strcmd);
DROPDOWNLIST1.ATTRIBUTES.ADD ("onchange", script);
22}
23
protected void Button1_Click (object sender, EventArgs e)
25 {
Response.Write ("I came from the server, has been saved!") ");
27}
28}
29}
30

Write JavaScript scripts on the page:

1 <script type= "Text/javascript" >
2 function confirmupdate (cmd)
3 {
4 if (Confirm ("Really want to save?"). "))
5 {
6 eval (cmd); The eval function calls a command contained in a string
7}
8 Else
9 {
Alert ("I am from the client, has been canceled!" ");
11}
12}
</script>

This triggers the OnChange client event when my DropDownList option is changed, and then the button server-side event is raised by the event.

Iv. ASP. NET event model mechanism

1, ASP. NET is a revolutionary change to the previous ASP, largely because the ASP is a new event-driven technology.
2. The triggering and processing of time in ASP is done on the client and server side.
3, ASP. NET, if frequently and the server carries on the event information transmission, can greatly reduce the server processing efficiency and the performance, therefore some events such as onmouseover did not provide;
4, but provides the change event, in order to improve the efficiency they are cached on the client, wait until the event information is sent to the server side together sent back.
such as the Change event for the text box, the change event for the drop-down box,
As in the change event for two controls:

1 protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e)
2 {
3 Response.Write ("DropDownList control selection Change!<br>");
4}
5
6 protected void textBox1_TextChanged (object sender, EventArgs e)
7 {
8 Response.Write ("TextBox text Changes!<br>");
9}

If the autopostback of the control itself is set to False (the default is False), the text box and drop-down boxes occur

When the change event is not executed, the event information is cached on the client,
when a server-side control button is clicked on the page,
         protected void Button1_Click (object sender, System.EventArgs e)
         {
           Response.Write ("click Button!< Br> ");
       }
   sends event information from the client to the server side, executes all events, and returns the message to the client:
TextBox text changed!
DropDownList control selection Change!
Clicked button! 

Specific example code see attachment.
Servertoclientscript.rar

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.