Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of event handling on the basis of ASP.NET Control Development

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you a sample analysis of event handling on the basis of ASP.NET control development. I hope you will gain something after reading this article. Let's discuss it together.

Event handling on the basis of ASP.NET control development. Postback events and client postback

Let's look at the simplest example.

Button click event

Protected void Button1_Click (object sender, EventArgs e) {Label1.Text = "Hello:" + TextBox1.Text;}

You know that there are three types of buttons created by Web server controls.

1.Button

2.LinkButton

3.ImageButton

Open MSDN and see that all three controls inherit the IPostBackEventHandler interface

IPostBackEventHandler interface specifically defines the method to handle postback events. To put it bluntly, it is the onclick event. If the custom control needs to handle postback events, you need to inherit the IPostBackEventHandler interface, and then implement the interface's RaisePostBackEvent method. Another simple method is to inherit the Button control directly.

The RaisePostBackEvent method is used to handle events raised when the form is sent to the server, with a parameter eventArgument that represents the String of the optional event parameter to be passed to the event handler

The following is a summary of the steps that must be taken to handle postback events

(1) inherit and implement the RaisePostBackEvent method of IPostBackEventHandler interface

(2) define a UniqueID for the form element to correspond to the UniqueID of the IPostBackEventHandler server control

The corresponding implementation code is as follows

Example one

Namespace CustomControls {public class SuperButton1: Control, IPostBackEventHandler {/ / declare Click event delegate public event EventHandler Click; / / define OnClick event handler protected virtual void OnClick (EventArgs e) {if (Click! = null) {Click (this, e) }} / / implement the RaisePostBackEvent method to handle the postback event public void RaisePostBackEvent (string eventArgument) {OnClick (EventArgs.Empty) } protected override void Render (HtmlTextWriter output) {output.Write ("< INPUT TYPE=submit name=" + this.UniqueID + "Value=' determine'/ >");}

If you are not familiar with delegation, you can refer to an article called a C # bedtime story.

EventArgs.Empty means that an event without event data should not be regarded as an empty event as I did before. I was very depressed at that time. Why trigger an empty event because I didn't see the meaning of the Empty field clearly? I thought it was empty.

EventArgs.Empty is equivalent to the constructor of the EventArgs class, equivalent to new EventArgs ()

Notice that the name property of the rendering control is also being rendered with UniqueID.

All right, now you can test it.

Protected void SuperButton1_1_Click (object sender, EventArgs e) {Label1.Text = "you clicked this button";}

In this way, you successfully define a control that handles postback events. Assuming that you use this control multiple times on the page, the compiler will generate a field for each event delegate instance. If the number of events is large, the storage cost of one delegate to one field may be unacceptable. . Therefore, another optimized event implementation is recommended.

The EventHandlerList class provides a simple list of delegates to add and remove. Let's take a look at the changed code.

AddHandler has two parameter event objects and an added delegate, which must be shown in the OnClick event to convert the delegate to the EventHandler type

Example two

Using System; using System.Web.UI; namespace CustomComponents {public class SuperButton2: Control, IPostBackEventHandler {/ / declare Click event delegate private static readonly object ClickKey = new object (); public event EventHandler Click {add {Events.AddHandler (ClickKey, value) } remove {Events.RemoveHandler (ClickKey, value);}} / / define OnClick event handler protected virtual void OnClick (EventArgs e) {EventHandler clickEventDelegate = (EventHandler) Events [ClickKey] If (clickEventDelegate! = null) {clickEventDelegate (this, e);}} / / implements the RaisePostBackEvent method to handle the postback event public void RaisePostBackEvent (string eventArgument) {OnClick (new EventArgs ()) } protected override void Render (HtmlTextWriter output) {output.Write ("< INPUT TYPE=submit name=" + this.UniqueID + "Value=' determine'/ >");}

Let's move on to client-side postback events. In HTML form elements, only Button buttons and ImageButton can cause a form postback.

However, if the LinkButton link button control wants to start a postback, it depends on the event mechanism of the client script to achieve its function.

In asp.net2.0, the button control has an additional UseSubmitBehavior property, indicating whether the Button control uses the client browser's submission mechanism (client postback) or ASP.NET postback mechanism. The postback mechanism is used by default. If set to false, you need to call the GetPostBackEventReference method to return the client postback event of Button.

When you set the UseSubmitBehavior property to flase, when you run the page, you will find a piece of automatically generated javascript code

The same is true of LinkButton. Let's take a look at the following example, which defines enumerations, button buttons and link buttons. When you test, you will find different effects when you open the source code.

Example three

Using System; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel Namespace CustomComponents {public enum ButtonDisplay {Button = 0, Hyperlink = 1} [ToolboxData ("< {0}: SuperButton3 runat=server > < / {0}: SuperButton3 >")] public class SuperButton3: Control, IPostBackEventHandler {public virtual ButtonDisplay Display {object display = ViewState ["Display"] If (display = = null) return ButtonDisplay.Button; else return (ButtonDisplay) display;} set {ViewState ["Display"] = value }} public virtual string Text {get {object text = ViewState ["Text"]; if (text = = null) return string.Empty; else return (string) text } set {ViewState ["Text"] = value;}} private static readonly object ClickKey = new object (); public event EventHandler Click {add {Events.AddHandler (ClickKey, value) } remove {Events.RemoveHandler (ClickKey, value);}} protected virtual void OnClick (EventArgs e) {EventHandler clickEventDelegate = (EventHandler) Events [ClickKey] If (clickEventDelegate! = null) {clickEventDelegate (this, e);}} public void RaisePostBackEvent (string argument) {OnClick (EventArgs.Empty);} override protected void Render (HtmlTextWriter writer) {base.Render (writer) Page.VerifyRenderingInServerForm (this); if (Display = = ButtonDisplay.Button) {writer.Write ("< INPUT type=\" submit\ "); writer.Write (" name=\ "" + this.UniqueID + "\"); writer.Write ("id=\"+ this.UniqueID +"\ ") Writer.Write ("value=\"+ Text +"\ "); writer.Write (" / > ");} else if (Display = = ButtonDisplay.Hyperlink) {writer.Write (" < A href=\ "); writer.Write (Page.GetPostBackClientHyperlink (this,")) Writer.Write ("\" > "+ Text +" < / A > ");}}

If you have already learned this knowledge and still have a score in mind, if not, if you are not familiar with some of the methods, you should take a look at MSDN. To put it more popularly, the postback event can be understood as the button click event, and the button is divided into two different postback event methods, so it is easier for people to accept, and the above is the way to realize the button click event.

Event handling on the basis of ASP.NET control development II. Data postback event

All right, let's move on to data postback. It is a little different from the event postback mentioned above.

Here is also a simple example. Look at the figure below. There are two DropDownList, one opens AutoPostBack, the other does not open, and then look at the following simple code, * DropDownList. When you change the value of the drop-down box, label does not display, press the OK button to display label, and the second DropDownList shows label when you change the value of the drop-down box, because AutoPostBack is turned on. We all understand this.

Protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e) {Label2.Text = "you chose:" + DropDownList1.SelectedItem.Text;} protected void DropDownList2_SelectedIndexChanged (object sender, EventArgs e) {Label1.Text = "you chose:" + DropDownList2.SelectedItem.Text;}

The principle of the above implementation is to judge the comparison between the old value and the new value (compare the data) in the SelectedIndexChanged event, and raise the event if there is a change, and the data postback is to realize such an event. Reorganize the train of thought to understand when the SelectedIndexChanged event will be raised

When selecting a drop-down box value, if the selected value is the same as the original value, the event is not triggered, and if the selected value is different from the original value, the SelectedIndexChanged event is triggered (or a comparison between the old value and the new value).

Open the MSDN document to view the DropDownList class and find that it inherits the IPostBackDataHandler interface. I mean, if you want to implement an event like Change, you have to inherit its interface. Take a look at MSDN's definition of this interface

IPostBackDataHandler interface

Defines the methods that ASP.NET server controls must implement in order to load postback data automatically.

The LoadPostData method determines whether to call the RaisePostDataChangedEvent method according to the change in the state of the server control due to a postback, and when it returns true, it is called (that is, when the old value is different from the new value).

The RaisePostDataChangedEvent method is used to raise any change event

The following example implements a TextChanged event like textbox

PostDataKey represents the key values of the internal data of the control, and postCollection represents the collection of all incoming name values, which are accessed by index

Using System; using System.Web; using System.Web.UI; using System.Collections.Specialized; using System.ComponentModel Namespace CustomComponents {[ToolboxData ("< {0}: Textbox1 runat=server > < / {0}: Textbox1 >"), DefaultProperty ("Text")] public class Textbox1: Control, IPostBackDataHandler {public string Text {get {object text = ViewState ["Text"] If (text = = null) return string.Empty; else return (string) text;} set {ViewState ["Text"] = value }} public bool LoadPostData (string postDataKey, NameValueCollection postCollection) {string postedValue = postCollection [postDataKey]; / / check new and old data if (! Text.Equals (postedValue)) {Text = postedValue; return true / / automatically call RaisePostDataChangedEvent ()} else return false; / / No change} public void RaisePostDataChangedEvent () {OnTextChanged (EventArgs.Empty) } protected virtual void OnTextChanged (EventArgs e) {if (TextChanged! = null) TextChanged (this, e);} public event EventHandler TextChanged; override protected void Render (HtmlTextWriter writer) {base.Render (writer); Page.VerifyRenderingInServerForm (this) Writer.Write ("< INPUT type=\" text\ "name=\"); writer.Write (this.UniqueID); writer.Write ("\" value=\ "" + this.Text + "/ >");}

The method implemented above is like the onclick event of button, but it is not true, but it is judged by sending back the old and new data. I added another example to the sample code, which is not listed here. You can download it and then look at it. You will understand that it is not the onclick event of button.

This time, I mainly talked about three basic event handling.

(1) capture postback events

(2) client script for callback

(3) processing postback data

The following two interfaces need you to be familiar with and use slowly.

IPostBackEventHandler interface and IPostBackDataHandler interface.

Think of the Button button to think of the IPostBackEventHandler interface, want to textbox,dropdownlist some change events want to want the IPostBackDataHandler interface, if you combine, and then think about it, you will understand more deeply.

After reading this article, I believe you have some understanding of "sample analysis of event handling on the basis of ASP.NET control development". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report