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
- 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.
- Set the updatemode attribute of the two updatepanel tagsConditional.
Program list 1: tag of default. aspx:
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
- Inherits="_Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-
- <title>Untitled Page</title>
-
- <body>
- <form id="form1" runat="server">
- <asp:ScriptManager EnablePartialRendering="true"
- ID="ScriptManager1" runat="server"></asp:ScriptManager>
- <div>
- <asp:UpdatePanel ID="UpdatePanel1" runat="server"
- UpdateMode="Conditional">
- <ContentTemplate>
- <asp:Label ID="Label1" runat="server" /><br />
- <asp:Button ID="Button1" runat="server"
- Text="Update Both Panels" OnClick="Button1_Click" />
- <asp:Button ID="Button2" runat="server"
- Text="Update This Panel" OnClick="Button2_Click" />
- </ContentTemplate>
- </asp:UpdatePanel>
- <asp:UpdatePanel ID="UpdatePanel2" runat="server"
- UpdateMode="Conditional">
- <ContentTemplate>
- <asp:Label ID="Label2" runat="server" ForeColor="red" />
- </ContentTemplate>
- <Triggers>
- <asp:AsyncPostBackTrigger ControlID="Button1"
- EventName="Click" />
- </Triggers>
- </asp:UpdatePanel>
- </div>
- </form>
- </body>
-
- 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)
- public partial class _Default : System.Web.UI.Page
- {
- protected void Button1_Click(object sender, EventArgs e)
- {
- Label1.Text = DateTime.Now.ToLongTimeString();
- Label2.Text = DateTime.Now.ToLongTimeString();
- }
-
- protected void Button2_Click(object sender, EventArgs e)
- {
- Label1.Text = DateTime.Now.ToLongTimeString();
- }
- }
- 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
- <%@ Page Language="C#" AutoEventWireup="true"
- CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-
-
- <title>Untitled Page</title>
-
- <body>
- <form id="form1" runat="server">
- <asp:ScriptManager EnablePartialRendering="true"
- ID="ScriptManager1" runat="server"></asp:ScriptManager>
- <div>
- <asp:UpdatePanel ID="UpdatePanel1" runat="server"
- UpdateMode="Conditional">
- <ContentTemplate>
- <asp:Label ID="Label1" runat="server" /><br />
- <asp:Button ID="Button1" runat="server"
- Text="Update Both Panels" OnClick="Button1_Click" />
- <asp:Button ID="Button2" runat="server"
- Text="Update This Panel" OnClick="Button2_Click" />
- <asp:CheckBox ID="cbDate" runat="server"
- Text="Include Date" AutoPostBack="false"
- OnCheckedChanged="cbDate_CheckedChanged" />
- </ContentTemplate>
- </asp:UpdatePanel>
- <asp:UpdatePanel ID="UpdatePanel2" runat="server"
- UpdateMode="Conditional">
- <ContentTemplate>
- <asp:Label ID="Label2" runat="server"
- ForeColor="red" />
- </ContentTemplate>
- <Triggers>
- <asp:AsyncPostBackTrigger ControlID="Button1"
- EventName="Click" />
- <asp:AsyncPostBackTrigger ControlID="ddlColor"
- EventName="SelectedIndexChanged" />
- </Triggers>
- </asp:UpdatePanel>
- <asp:DropDownList ID="ddlColor" runat="server"
- AutoPostBack="true"
- OnSelectedIndexChanged="ddlColor_SelectedIndexChanged">
- <asp:ListItem Selected="true" Value="Red" />
- <asp:ListItem Value="Blue" />
- <asp:ListItem Value="Green" />
- </asp:DropDownList>
- </div>
- </form>
- </body>
-
The code file is as follows:
Program list 4: code files
- public partial class _Default : System.Web.UI.Page
- {
- protected void Button1_Click(object sender, EventArgs e)
- {
- if (cbDate.Checked)
- {
- Label1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
- Label2.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
- }
- else
- {
- Label1.Text = DateTime.Now.ToLongTimeString();
- Label2.Text = DateTime.Now.ToLongTimeString();
- }
- }
-
- protected void Button2_Click(object sender, EventArgs e)
- {
- if (cbDate.Checked)
- {
- Label1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
- }
- else
- {
- Label1.Text = DateTime.Now.ToLongTimeString();
- }
- }
-
- protected void cbDate_CheckedChanged(object sender, EventArgs e)
- {
- cbDate.Font.Bold = cbDate.Checked;
- }
-
- protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
- {
- Color c = Color.FromName(ddlColor.SelectedValue);
- Label2.ForeColor = c;
- }
- }
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!