Understanding ASP. NET Ajax updatepanel triggers (2)

Source: Internet
Author: User
Tags reflector

Introduction

Microsoft's ASP. NET technology provides an object-oriented, event-driven programming model that combines the advantages of compiled code. However, the server-side processing model still has some technical limitations, many of which can be solved by the new features of Microsoft ASP. NET 3.5 Ajax extensions. These extensions provide a large number of new client features, including partial page rendering without refreshing the entire page, through client scripts (including ASP.. Net configuration file API) access web services and a wide range of client-side APIs, used to map ASP.. NET Server-side controls.

This White Paper will introduce ASP. NET Ajax in DepthUpdatepanelThe XML trigger function of the component. XML triggers allow you to precisely control components that provide the partial display function of a specific updatepanel control.

This White Paper is based on. NET Framework 3.5 beta 2 and Visual Studio 2008. ASP. NET Ajax extensions, which was previously used as an ASP. NET 2.0 plug-in assembly, is now integrated into the. NET Framework basic class library. This White Paper also assumes that the reader is using Visual Studio 2008 instead of Visual Web Developer express and will provide rehearsals Based on the Visual Studio User Interface (regardless of the development environment used, the code list will be fully compatible ).

Trigger

By default, a trigger for a given updatepanel automatically contains all sub-controls for calling the callback, including (for example)AutopostbackProperty is setTrueTextbox Control. However, you can also include the trigger with a tag declarative. This operation is declared in the updatepanel Control<Triggers>Partially completed. Although you can useTriggersSet attribute access trigger, but we recommend that you register a partial display trigger at runtime (for example, if a control is unavailable during design ):Page_loadEvent, useRegisterasyncpostbackcontrol (Control)Method. Remember that the page is stateless. Therefore, you must re-register the controls each time you create them.

By addingChildrenastriggersSet propertyFalse, You can disable the function of automatically containing the sub-trigger (in this way, the sub-control that creates the return will not automatically trigger partial rendering ). This allows you to enjoy maximum flexibility when specifying controls that can be rendered on pages. Therefore, this method is recommended. In this way, developers will respond to events in the form of "decision to participate", rather than handling any possible events.

Note: When the updatepanel control is nested, if you set updatemodeConditionalIf the child updatepanel is triggered but the parent updatepanel is not triggered, only the child updatepanel is refreshed. However, if the parent updatepanel is also refreshed, the Child updatepanel will also be refreshed.

<Triggers> element

When using the tag editor in Visual Studio, you may (from intelliisense) notice that an updatepanel control has two child elements. The most common element is<Contenttemplate>It essentially encapsulates the content that will be contained by the update Panel (that is, the content that we implement partial rendering ). Another element is<Triggers>Used to specify the control on the page (or the user control you are using), this control will trigger<Triggers>Partial rendering of the updatepanel to which the element belongs.

<Triggers>An element can contain each of the following two byte points with unlimited quantity:<Asp: asyncpostbacktrigger>And<Asp: postbacktrigger>. Both subnodes accept two attributes:ControlidAndEventnameAnd you can specify any control in the current encapsulation unit (for example, if your updatepanel control is located in a Web user control, you should not try to reference the control on the page where the user control will be placed ).

<Asp: asyncpostbacktrigger>The biggest use of an element is that it can be used from the encapsulation UnitAnyThe child control of the updatepanel control specifies the event, not just the parent updatepanel of the trigger. In this way, any control can trigger partial page update.

Similarly,<Asp: postbacktrigger>The element can be used to trigger partial page rendering, but requires a complete round-trip to the server. This trigger element can also be used to trigger partial page rendering normally when the control does not have an exception (for example, when the updatepanel Control<Contenttemplate>There isButtonTo forcibly display the complete page. Similarly, the postbacktrigger element specifies any child control of any updatepanel control in the current encapsulation unit.

<Triggers> element reference

Mark subitem:

Tag

Description

<Asp: asyncpostbacktrigger>

If a control or event is specified, a partial page update containing the updatepanel referenced by the trigger is triggered.

<Asp: postbacktrigger>

Specify a control and event that will trigger a full page update (the whole page is refreshed. This flag can be used to force the full page rendering when the partial page rendering is triggered normally if the control does not have an exception.

Walkthrough: Cross-updatepanel trigger
  1. Create an ASP. NET page and create a scriptmanager object set to enable partial rendering. Add two updatepanel controls to the new page: Add a label control (label1), and then add two button controls (button1 and button2 ). The text of button1 is "click to update both", and button2 is "click to update this" or similar content. Add only one label control (label2) in the second updatepanel, but set its forecolor attribute to a value other than the default value for difference.
  2. Set the updatemode attribute of the two updatepanel tagsConditional.

Program list 1: tag of default. aspx:


 
 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
  2. Inherits="_Default" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  4.      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5.      
  6.           <title>Untitled Page</title>
  7.      
  8.      <body>
  9.           <form id="form1" runat="server">
  10.                <asp:ScriptManager EnablePartialRendering="true"
  11.                     ID="ScriptManager1" runat="server"></asp:ScriptManager>
  12.                <div>
  13.                     <asp:UpdatePanel ID="UpdatePanel1" runat="server"
  14.                          UpdateMode="Conditional">
  15.                          <ContentTemplate>
  16.                               <asp:Label ID="Label1" runat="server" /><br />
  17.                               <asp:Button ID="Button1" runat="server"
  18.                                    Text="Update Both Panels" OnClick="Button1_Click" />
  19.                               <asp:Button ID="Button2" runat="server"
  20.                                    Text="Update This Panel" OnClick="Button2_Click" />
  21.                          </ContentTemplate>
  22.                     </asp:UpdatePanel>
  23.                     <asp:UpdatePanel ID="UpdatePanel2" runat="server"
  24.                          UpdateMode="Conditional">
  25.                          <ContentTemplate>
  26.                               <asp:Label ID="Label2" runat="server" ForeColor="red" />
  27.                          </ContentTemplate>
  28.                          <Triggers>
  29.                               <asp:AsyncPostBackTrigger ControlID="Button1" 
  30.                                EventName="Click" />
  31.                          </Triggers>
  32.                     </asp:UpdatePanel>
  33.                </div>
  34.           </form>
  35.      </body>
  1. In the click event handler of button1, set label1.text and label2.text to time-independent values (such as datetime. Now. tolongtimestring ()). In the click event handler of button2, only label1.text is set to a value unrelated to time.

Program list 2: code files in default. aspx. CS (processed)


 
 
  1. public partial class _Default : System.Web.UI.Page
  2. {
  3.      protected void Button1_Click(object sender, EventArgs e)
  4.      {
  5.           Label1.Text = DateTime.Now.ToLongTimeString();
  6.           Label2.Text = DateTime.Now.ToLongTimeString();
  7.      }
  8.  
  9.      protected void Button2_Click(object sender, EventArgs e)
  10.      {
  11.           Label1.Text = DateTime.Now.ToLongTimeString();
  12.      }
  13. }
  1. Press F5 to run the project. Note: When you click Update both panels, the text of both labels changes. However, when you click Update this panel, only label1 is updated.

Insider and decryption

Using the example we just created, we can understand the role of ASP. NET Ajax and how updatepanel triggers work across layers. To this end, we will use the source HTML of the generated page and the Mozilla Firefox extension called firebug, which will help us to view Ajax backhaul more conveniently. We will also use Lutz roeder's. Net reflector. All the above tools can be downloaded from the Internet for free and can be found through Internet search.

The page source code check shows that there are almost no exceptions. The updatepanel control is rendered<Div>Container, and we can see<Asp: scriptmanager>The source of the provided foot. In addition, there are some new Ajax-specific calls to pagerequestmanager In the Ajax client script library. Finally, we can see two updatepanel containers. One of them is rendered<Input>Button and two<Span>Container<Asp: Label>Control. (If you view the DOM tree in firebug, you can see that the labels are dimmed, indicating that they do not produce visible content .)

Click the update this panel button. Note that the updatepanel at the top will be updated to the current server time. Select the console tab in firebug to view requests. First, check the POST request parameters:

Note: The updatepanel Ajax code on the server accurately indicates which control is triggered by the scriptmanager1 parameter:That is, updatepanel1ControlButton1. Click Update both panels. Then, view the response. We will see a string consisting of a series of variable sets separated by vertical bars. The updatepanel at the top isUpdatepanel1To the browser. The Ajax client script library uses. InnerhtmlAttribute. The new content replaces the original HTML content of updatepanel. Therefore, the server sends the changed content as HTML.

Click Update both panels to view the results returned from the server. The results are similar: Both updatepanel receive the new HTML from the server. Like the previous call, other page statuses are sent.

As we can see, because no special code is used to execute Ajax return, the Ajax client script library can intercept form return without any additional code. The server control automatically uses JavaScript so that forms do not need to be submitted automatically: Asp. net has been automatically injected with code to complete Form Verification and status settings, mainly by the automatic script resource inclusion, postbackoptions class and clientscriptmanager class.

For example, you want to perform this operation on a checkbox control. Check the class disassembly program in. Net reflector. Operation Method: Make sure that your system. Web assembly is open and navigateSystem. Web. UI. webcontrols. checkboxClass, openRenderinputtagMethod. Find a checkAutopostbackAttribute conditions:

WhenHeckboxWhen automatic callback is enabled on the control (the autopostback attribute is set to true ),<Input>When marking, itsOnclickThere will be an ASP. NET event processing script in the property. Then, you can intercept the submitted form to allow ASP. NET Ajax injection into the page without any impact. This helps prevent compatibility changes caused by possible insertion of inaccurate strings. In additionAnyYou can use ASP. NET ajax to customize ASP. NET controls without adding code to support ASP. NET Ajax in the updatepanel container.

<Triggers>The function corresponds to the value initialized in the call of pagerequestmanager to _ updatecontrols (note ASP. net Ajax client script library uses the Convention that "the methods, events, and field names starting with the following line are marked as internal and cannot be used separately outside the library, you can view which controls are used to trigger Ajax return.

For example, we add two additional controls to the page, one of which is placed completely out of updatepanel and the other within updatepanel. We will add a checkbox control in the above updatepanel and add a dropdownlist that defines multiple colors. The new tag is as follows:

Program list 3: new tag


 
 
  1. <%@ Page Language="C#" AutoEventWireup="true"
  2.      CodeFile="Default.aspx.cs" Inherits="_Default" %>
  3.  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  5.      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6.  
  7.      
  8.           <title>Untitled Page</title>
  9.      
  10.      <body>
  11.           <form id="form1" runat="server">
  12.                <asp:ScriptManager EnablePartialRendering="true"
  13.                     ID="ScriptManager1" runat="server"></asp:ScriptManager>
  14.                <div>
  15.                     <asp:UpdatePanel ID="UpdatePanel1" runat="server"
  16.                          UpdateMode="Conditional">
  17.                          <ContentTemplate>
  18.                               <asp:Label ID="Label1" runat="server" /><br />
  19.                               <asp:Button ID="Button1" runat="server"
  20.                                    Text="Update Both Panels" OnClick="Button1_Click" />
  21.                               <asp:Button ID="Button2" runat="server"
  22.                                    Text="Update This Panel" OnClick="Button2_Click" />
  23.                               <asp:CheckBox ID="cbDate" runat="server"
  24.                                    Text="Include Date" AutoPostBack="false"
  25.                                    OnCheckedChanged="cbDate_CheckedChanged" />
  26.                          </ContentTemplate>
  27.                     </asp:UpdatePanel>
  28.                     <asp:UpdatePanel ID="UpdatePanel2" runat="server"
  29.                          UpdateMode="Conditional">
  30.                          <ContentTemplate>
  31.                               <asp:Label ID="Label2" runat="server"
  32.                                    ForeColor="red" />
  33.                          </ContentTemplate>
  34.                          <Triggers>
  35.                               <asp:AsyncPostBackTrigger ControlID="Button1" 
  36.                                    EventName="Click" />
  37.                               <asp:AsyncPostBackTrigger ControlID="ddlColor" 
  38.                                    EventName="SelectedIndexChanged" />
  39.                          </Triggers>
  40.                     </asp:UpdatePanel>
  41.                     <asp:DropDownList ID="ddlColor" runat="server"
  42.                          AutoPostBack="true"
  43.                          OnSelectedIndexChanged="ddlColor_SelectedIndexChanged">
  44.                          <asp:ListItem Selected="true" Value="Red" />
  45.                          <asp:ListItem Value="Blue" />
  46.                          <asp:ListItem Value="Green" />
  47.                     </asp:DropDownList>
  48.                </div>
  49.           </form>
  50.      </body>

The code file is as follows:

Program list 4: code files


 
 
  1. public partial class _Default : System.Web.UI.Page
  2. {
  3.      protected void Button1_Click(object sender, EventArgs e)
  4.      {
  5.           if (cbDate.Checked)
  6.           {
  7.                Label1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
  8.                Label2.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
  9.           }
  10.           else
  11.           {
  12.                Label1.Text = DateTime.Now.ToLongTimeString();
  13.                Label2.Text = DateTime.Now.ToLongTimeString();
  14.           }
  15.      }
  16.  
  17.      protected void Button2_Click(object sender, EventArgs e)
  18.      {
  19.           if (cbDate.Checked)
  20.           {
  21.                Label1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
  22.           }
  23.           else
  24.           {
  25.                Label1.Text = DateTime.Now.ToLongTimeString();
  26.           }
  27.      }
  28.  
  29.      protected void cbDate_CheckedChanged(object sender, EventArgs e)
  30.      {
  31.           cbDate.Font.Bold = cbDate.Checked;
  32.      }
  33.  
  34.      protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
  35.      {
  36.           Color c = Color.FromName(ddlColor.SelectedValue);
  37.           Label2.ForeColor = c;
  38.      }
  39. }

The idea on this page is to select one of the three colors from the drop-down list to display the second tag. The check box determines whether the label is bold and whether the label displays the date and time. The check box should not trigger Ajax updates, but the drop-down list should be triggered, even if it is not in updatepanel.

From the screen above, we can clearly see that the last button clicked is the update this panel on the right, which updates the time above, regardless of the time at the bottom. The date display is disabled by clicking, because only the date display is shown below. The last interesting thing is the color of the bottom label: it is updated later than the label text, which indicates that the control status is very important and the user wants to retain it through Ajax return.However, Time not updated.When the control is re-displayed on the server, the time is automatically refilled by saving the _ viewstate field on the page explained during ASP. NET runtime. The ASP. NET Ajax server code does not recognize the methods in which the control changes its status. It just refills the view status and then runs the appropriate event.

However, it should be noted that if we previously initialized the time in the page_load event, the time will be correctly displayed. Therefore, developers should pay attention to running the appropriate code in the appropriate event handler, and avoid using page_load when the control event handler is suitable.

Summary

ASP. NET Ajax extensions updatepanel controls are used in many ways to identify control events that cause updates. It supports automatic update through its own child controls, and can also respond to control events at other locations on the page.

We recommend that you set the updatepanelChildrenastriggersAttribute Value:FalseAnd set the event to "select to participate" instead of containing the event by default. This also prevents unnecessary results from unnecessary events, including verification and changes to input fields. These types of bugs may be difficult to isolate, because page updates are transparent to users, and the cause may not be immediately visible.

By checking ASP. net Ajax form posting intercepts the internal operation of the model, we can determine that it uses ASP. net has already provided a framework to maintain maximum compatibility with controls designed using the same framework, and minimize the amount of JavaScript code written on the page.

Happy programming!

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.