ASP.net 2.0 server controls to process the postback data

Source: Internet
Author: User
Tags define bool empty implement interface key requires return
Asp.net| Server | control | data

Implementing events for custom server controls is a more complex process. Not only do developers need to capture the postback event based on the methods described in the previous article, but they also sometimes need to participate in the postback data processing process. This article will introduce a method of processing the return data through a typical application.

  1. Implement processing return Data

In the process of capturing a return event, which is described in the previous article, the control data that is uploaded to the server is often not involved. Developers primarily implement the IPostBackEventHandler interface to successfully capture events and define event handlers for them. However, some server controls in the application process, involving the changes in the return data and so on. For example, a custom control is an input control that, when entered and returned by a user, may cause events due to changes in the postback data. To handle the above issues, the control class must implement the IPostBackDataHandler interface. The following is an enumeration of interface declaration codes.

Public interface ipostbackdatahandler{public bool LoadPostData (string postdatakey, NameValueCollection postcollection ); public void RaisePostDataChangedEvent ();}

The IPostBackDataHandler interface is used when creating a server control that requires form data to be uploaded by the client to the server. As shown in the code above, the interface includes two methods, LoadPostData and RaisePostDataChangedEvent.

Similar to the implementation capture postback event, it is not complete to implement the interface in the control class alone. The following is a summary of the two key points that must be implemented in order to achieve processing of the postback data.

First, the property value of the control's name must be set to UniqueID in the control rendering. This is because after a postback occurs, the page framework will search for a value that matches the UniqueID of the server control that implements IPostBackDataHandler, before the LoadPostData method can be invoked.

Second, the control class must implement the IPostBackDataHandler interface and implement the LoadPostData and RaisePostDataChangedEvent methods. The LoadPostData method is used to check the data submitted to the server. The method contains two parameters: Postdatakey represents the key value used to identify the data within the control, PostData is a collection of submitted data that is accessible using the Key/value structure for index names. To access the control data in the collection, simply use the following code: "String ndata = Postdata[postdatakey];" "。 In the LoadPostData method, the method return value is determined by comparing the new data (the data value sent by the client) to the old data (the data value previously submitted to the client). If the old and new data are the same, the data has not been modified, the method return value is false, and if the old data is different, it indicates that the legacy has been modified by the client and the method returns the value TRUE. The following is a simple application of the LoadPostData method.

Public virtual bool LoadPostData (string postdatakey,namevaluecollection postdata)
{
string PresentValue = Text;
Old data
String postedvalue = postdata[postdatakey];//new data
Check for old and new data
if (presentvalue.equals (postedvalue) | | | presentvalue = = NULL) {
Text = Postedvalue;
return true;
}
return false;
}

If the LoadPostData method returns True. NET Framework will automatically invoke the RaisePostDataChangedEvent method. This method signals that the server control object notifies the ASP.net application that the state of the control has changed, and that the control developer can define the event that is raised based on the data change in the method. The following is a simple call to the OnTextChanged method:

public virtual void RaisePostDataChangedEvent ()
{
OnTextChanged (Eventargs.empty);
}

The above is the key point to deal with the return data, and mastering these points is very important for event processing. At the same time, its content also explains the following. NET Framework processes the process of returning data:

(1) First search for the value that matches the UniqueID of the server control that implements IPostBackDataHandler in the content being sent.

(2) Call the LoadPostData method and return the bool value.

(3) If the LoadPostData method returns True, then the RaisePostDataChangedEvent method is invoked.

(4) Perform the OnEvent method defined in the RaisePostDataChangedEvent method.

  2. Typical applications

The following is a typical example to illustrate the core process of processing the postback data. Creates a custom text box control, whose Text property Webcustomcontrol changes as a result of the postback. Control raises the TextChanged event after loading the postback data. The control class source code looks like this:

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Text;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace webcontrollibrary{
[Defaultproperty ("Text")]
[ToolBoxData ("<{0}:webcustomcontrol runat=server> </{0}:WebCustomControl>")]
public class Webcustomcontrol:webcontrol, IPostBackDataHandler {
Implementing the Text Property
[Bindable (True)]
[Category ("appearance")]
[DefaultValue ("")]
[Localizable (true)]
public string Text {
get {
string s = (string) viewstate["Text"];
Return ((s = = null)? STRING.EMPTY:S);
}
set {
viewstate["Text"] = value;
}
}
Overriding the control rendering method rendercontents
protected override void RenderContents (HtmlTextWriter output) {
Output. AddAttribute (Htmltextwriterattribute.type, "text");
Output. AddAttribute (Htmltextwriterattribute.value, Text);
Output. AddAttribute (Htmltextwriterattribute.name, this. UniqueID);
Output. RenderBeginTag (Htmltextwritertag.input);
Output. RenderEndTag ();
}
Defining Event Objects Eventtextchanged
private static readonly Object eventtextchanged = new Object ();
#region Realize IPostBackDataHandler Members
BOOL Ipostbackdatahandler.loadpostdata (String Postdatakey, System.Collections.Specialized.NameValueCollection Postcollection) {
Compare initial data PresentValue and postback data postedvalue
String postedvalue = Postcollection[postdatakey];
string PresentValue = Text;
if (PresentValue = null | | Postedvalue!= presentvalue) {
Text = Postedvalue;
return true;
}
return false;
}
void Ipostbackdatahandler.raisepostdatachangedevent () {
OnTextChanged (Eventargs.empty);
}
#endregion//Implement event handlers OnTextChanged
private void OnTextChanged (EventArgs EventArgs) {
EventHandler Textchangedhandler = (EventHandler) events[eventtextchanged];
if (Textchangedhandler!= null) {
Textchangedhandler (this, EventArgs);
}
}
Implement event property structure for TextChanged
Public event EventHandler TextChanged {
Add {
Events.addhandler (eventtextchanged, value);
}
Remove {
Events.removehandler (eventtextchanged, value);
}
}
}
}

The above source code implements some important content.

(1) The control class must implement IPostBackDataHandler, which enables the control to participate in the postback data processing.

(2) Defines the property text, whose property values are stored in viewstate. When the page is returned, the viewstate containing the value of the Text property is committed to the server.

(3) Rewrite the RenderContents method and define the control rendering logic in the method.

(4) The method of realizing IPostBackDataHandler LoadPostData. Compares the data values sent by the client to the same data values that the previous server submitted to the client. Returns False if the data is the same, if the data is not modified, and if the data is different, it indicates that the data has been modified by the client.

(5) The method of realizing IPostBackDataHandler raisepostdatachangedevent. If the return value of LoadPostData is true, the method is executed, requiring that the OnTextChanged method be invoked.

(6) Define event property structure TextChanged. In the Events delegate list, define the add and remove accessors for the Eventtextchanged event delegate object.

(7) Define the OnTextChanged method.

The following is the Default.aspx source code that applies the custom server control:

<%@ Page language= "C #" autoeventwireup= "true" codefile= "Defau Lt.aspx.cs "inherits=" _default "%>
<%@ Register tagprefix=" WCL "assembly=" Webcontrollibrary "namespace=" Webcontrollibrary "%>
"! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">



Process postback data </ title>













html>

In the above code, you define a Webcustomcontrol control and define the handling method demo1_textchanged for the TextChanged event for the control. This method requires that the Text property value of the label control be modified. The effect figure is shown in Figure 1 and Figure 2.


Figure 1 Page initialization Effect Diagram 2 page submission effect chart

Some readers may misunderstand that the above example defines the event handling method for the Click event of the Submit button. Actually, otherwise. This example does not define the handle for the Click event for the Submit button, but rather by processing the postback data and defining the TextChanged event for the Webcustomcontrol control.

   3. Summary

In this paper, the realization method of processing return data is introduced. Mastering these elements will provide a good basis for developing high-quality server controls. At this point, through the introduction of three articles, I believe that readers have mastered the basic method of implementing events for custom server controls. In subsequent content, I will continue to introduce the use of ASP.net 2.0 technology to create additional content for server controls.



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.