Whether it is good or bad, the updatepanel control is a favorite of the ASP. NET Ajax Community. I say "good" because updatepanel makes rendering some pages quite simple, but "bad" is because its simplicity and ease of use are at the cost of efficiency and ridiculous bandwidth.
Updatepanel can bring Ajax magical benefits to general web pages, but it cannot provide the efficiency of normal association with Ajax. For example, do you know that when the updatepanel Control performs asynchronous Ajax callback on the server to update its content, this request contains the regular ASP. net, including view status? Most developers think That Ajax cancels the view status. The Ajax brand of updatepanel does not.
If you want to use the updatepanel control, you need to know what you are doing. In many cases, from a performance perspective, it is better for an application to use Asynchronous calls to webmethods or page methods instead of updatepanel. This may significantly reduce the amount of data transmitted over the network. However, it is also a fundamental change. Here, UI updates need to be explicitly processed by developers using JavaScript on the page.
In addition, questions about custom updatepanel are everywhere on the ASP. NET Ajax forum. In fact, as long as you understand the MicrosoftThe pagerequestmanager and JavaScript classes in the Ajax library can solve many problems.
Now that ASP. NET Ajax is provided, I want to further check updatepanel to learn more about how you can customize and optimize it, and even how to run it without it. This is exactly what this column contains.
Update highlight
Sometimes you cannot help Microsoft developers, but you can only regret them. If they cannot do their jobs well enough, they will be criticized by the public. However, sometimes they do a great job and are under criticism. For example, I recently received an email from a Customer complaining that ASP. NET Ajax updatepanel is a little overrunning.
Updatepanel enables ASP. Net pages to be sent back to the server and makes it extremely easy to flash and flash when it becomes a smooth, non-blinking update. Updatepanel can exert its magic by converting a sending back to an asynchronous callback (XML-HTTP request), and using JavaScript on the client to refresh Part of the page encapsulated by the updatepanel control. Flash and flash will disappear because the browser will not redraw the page as it is during the sending back.
The customer complained that the user sometimes does not notice that the part of the page has been updated. His question is simple: Does the ASP. NET Ajax team make updatepanel flash a little more so that users do not miss important updates?
Unfortunately, the ASP. NET Ajax team may not be interested in making updatepanel flashes. After all, eliminating flickering is the original intention of updatepanel. However, you can use some magical functions of Ajax in your browser to attract the attention of updated updatepanel. The secret lies in the SYS. webforms. pagerequestmanager class in Microsoft Ajax Library (a library of JavaScript classes consisting of half of ASP. NET Ajax on the client. Pagerequestmanager can manage asynchronous callbacks started by updatepanel. It is also responsible for updating the content in updatepanel after the asynchronous callback is complete.
Pagerequestmanager can trigger events in the browser before and after the update. You can associate these events in JavaScript and run the code to remind users to update the content. The key event is named pageloaded. This event triggers page loading in the browser every time (similar to page_load in ASP. NET ). It also triggers an asynchronous callback that represents the completion of the updatepanel control and updates the content in the updatepanel. You can use two lines of code (which can be merged into one line) to register the Javascript handler for the pageloaded event:
var prm = Sys.WebForms.PageRequestManager.getInstance();prm.add_pageLoaded(pageLoaded);
The first line gets a reference to the page's pagerequestmanager object. The second line registers the JavaScript function named pageloaded as the handler for the pageloaded event.
During the call, the pageloaded event handler receives a sys. webforms. pageloadedeventargs-type parameter, which is another class in Microsoft Ajax library. Pageloadedeventargs contains a get_panelsupdated method. You can call this method to enumerate all updatepanel (if any), whose content has just been updated. By default, updatepanel is the DIV on the client. Therefore, you can use JavaScript to make the DIV flash, highlight it, or perform any operations you want on it, to remind users to pay attention to it.
The Code listed in figure 1 shows a method for updating the highlighted display using the pageloaded event. Each time an update is made, this JavaScript will flash the Document Object Model (DOM) elements that represent the updated updatepanel by making them quickly displayed and hidden three times in sequence. Flash is executed through the Helper function named flashpanels, which uses the number of flashes as the input parameter.
Note that the updated updatepanel visibility can be switched on and off to create a flash effect. In addition to directly interacting with DOM elements, the Code also encapsulates DOM elements representing updatepanel with sys. UI. control objects. Then, it uses the set_visible and get_visible methods of SYS. UI. Control to switch visibility:
_panels[i].set_visible(!_panels[i].get_visible());
SYS. UI. Control is a javascript class found in Microsoft Ajax library, specifically microsoftajax. js. The advantage of switching visibility in this way is that it is independent from the browser. This operation is equally effective in every browser that supports ASP. NET Ajax (almost all modern browsers. On the other hand, JavaScript code that interacts directly with the browser Dom must be adjusted for use in different browser types.
Cancel updatepanel update
The pageloaded event is one of several events triggered by the pagerequestmanager class when updatepanel returns the server to update its content. Another important event triggered by pagerequestmanager is initializerequest, which is triggered before an asynchronous callback occurs.
Recently, someone asked me if it is possible to decide whether to allow asyncpostbacktrigger to trigger an updatepanel update during runtime. The answer is yes. This operation is completed by processing the initializerequest event.
The second parameter passed to the initializerequest handler is an object of the initializerequesteventargs type. This object contains the get_postbackelement method, which can identify the button or other elements that trigger the update. It also has a set_cancel method that you can use to cancel before the callback occurs. The following is an example of the set_cancel method in use:
<script type=”text/javascript”>var prm = Sys.WebForms.PageRequestManager.getInstance();prm.add_initializeRequest(initializeRequest);function initializeRequest(sender, args){args.set_cancel(!confirm(‘Are you sure?’));}</script>
In this example, the intializerequest handler can pop up a confirmation box before the callback execution to ask whether the user wants to continue the update. Click "cancel" (cancel) in the confirmation box to pass "true" to set_cancel to stop executing the callback. In real life, you may feel that it is not necessary to prompt the user to confirm before continuing the update, but it may be useful if the update can be canceled based on conditions elsewhere in the application.
By the way, it may cancel asynchronous callback execution before it is completed. Pagerequestmanager provides the abortpostback method to perform this operation. It also provides the get_isinasyncpostback method to determine whether asynchronous callback is suspended. These methods are usually used with the updateprogress control to display and cancel the UI.
Multiple updatepanel
A page can host several updatepanels. By default, when updatepanel on a page is updated, other updatepanel on the page is also updated. Sometimes this is what you want, but most of you do not need every updatepanel update to respond to other updatepanel.
By setting the updatemode attribute of each updatepanel control on the page to conditional, you can select the updatepanel instance to be updated (and the Update time ). Then, when updatepanel updates and calls the server-side event handler, call updatepanel. Update on the other panel you want to update. In this way, the server load can be reduced by reducing the number of rendered controls, and it also reduces the data volume in the response, because updatepanel without updating will not add any data to the response.
Do not use updatepanel update
Ajax not only creates a better user experience, but also provides more efficient network communication. When the traditional ASP. NET sending back occurs, all data in the web form, including the view status, will be transmitted to the server in the sending back. The view status is an ASP. NET page, especially the ASP. NET page of The DataGrid and gridview control, which seems to be slow. Pages with too many view statuses will degrade performance, and pages with too many view statuses are too common in ASP. NET applications.
One of the advantages of replacing ASP. Net with Ajax callback is that it can be completed correctly. Ajax callback only transmits the data to be transmitted. This means that they do not have to include view states in the transmission.
When you use updatepanel to perform non-blinking updates on a page, you may think that you are building an efficient website. After all, updatepanel uses Ajax, isn't it? Unfortunately, if you check the communication in the network when updatepanel is updated, you will find that you have not saved anything at all, at least at the time of sending. View status data (and other data) transmitted to the server during sending-back is also transmitted during the updatepanel callback. In fact, the growth in asynchronous XML-HTTP requests from updatepanel is almost the same as that in standard ASP. NET sending. The following are some secrets related to ASP. NET Ajax: Although updatepanel is easy to use, its communication efficiency is not high.
There is almost no way to improve the efficiency of updatepanel, but you can stop using updatepanel and switch to ASP. other functions of net Ajax are used to update page content, which is not only the same but also more efficient. It only requires a little effort, but the final result is often considered worthwhile, because you can greatly reduce the amount of data transmitted between the client and the server.
You can also reduce the load on the server. When updatepanel calls back to the server, the page that is called back as the target will complete almost the entire lifecycle-the page will be instantiated and the controls on the page will also be instantiated, in addition, the control in updatepanel completes a normal rendering loop. This is a huge overhead for updating part of the web page.
For example, consider the page section in Figure 2. It provides a simple UI that allows users to enter a zip code and click the button to initialize the city and state fields (see figure 3 ). All controls are carried in updatepanel. Therefore, the callback of the button control is converted to an asynchronous callback, and the event handler (getcityandstate) is called to the internal server of the callback. Getcityandstate (undisplayed code) reads the zip code from the zip code text box, converts it to the city and state, and initializes the textbox and dropdownlist representing the City and State accordingly. Since all these occur within the updatepanel, the update is smooth and does not flash.
Figure 3 city, state, and zip code UI (click the image to get a small view)
Figure 3 city, state, and zip code UI (click the image to get a large view)
Now there is a problem. Updatepanel has used this method to improve user experience, but it cannot reduce the amount of data transmitted over the network. Updatepanel can hardly reduce the load on the server, until the internal control of updatepanel is displayed, the processing performed on the server is almost the same as that occurred during the complete sending back process. This method must be used, because one of the advantages of the updatepanel control is that the operations performed by the server-side event handler (such as getcityandstate) in the asynchronous callback are the same as those performed in the traditional sending back. This means that the controls on the page must be instantiated and they must have the right to access the view status.
Figure 4 shows how to implement the same function without using the updatepanel control. This time, the AutoFill button was bound to a javascript that inspired asynchronous XML-HTTP requests to the asmx web method named getcityandstate. This call is put through the Javascript proxy named zipcodeservice, which is generated by the service reference in the scriptmanager control. Getcityandstate uses the zip code string as the input, and returns a string array containing the corresponding city and state items. The ongetcityandstatecompleted function retrieves the items in the array and inserts them into the city and state fields. The results seem to be the same from the outside, but the internal running mode is quite different.
The following describes how to call the asmx web method through a javascript Proxy:
[ScriptService]public class ZipCodeService : System.Web.Services.WebService{[WebMethod]public string[] GetCityAndState(string zip){...}}
In addition to its class attribute being scriptservice, rather than WebService, This is a standard web method from all aspects. Although scriptservice has the same meaning as WebService, it also contains the additional meaning, that is, webmethods of web services can be called from client scripts.
In addition to allowing regular webmethods to act as the destination for XML-HTTP requests, ASP. NET Ajax also supports a special type of web method called the PAGE method. The page method is webmethods implemented on the web page, that is, in the aspx file or codebehind file, rather than in the asmx file. The page method allows developers to provide endpoints used for XML-HTTP callbacks without building professional web services.
The page method must be a public static method, and must have the webmethod attribute like webmethods. (Webmethods and page methods can also have the scriptmethod attribute, which provides additional controls for exiting the network .) On the client side, the page method can be called from JavaScript through a special pagemethods proxy.
Unlike Web Services, page methods do not require service reference. However, you must enable the PAGE method by setting the enablepagemethods attribute of the scriptmanager control to true, as shown below:
<asp:ScriptManager ID=”ScriptManager1” runat=”server”EnablePageMethods=”true” />
In essence, the page method provides the same efficiency as webmethods. When the PAGE method is called, view status and other inputs are not transferred to the server. Since the page methods are static, you can call them without instantiating page objects. The call to the page method does not call the page lifecycle triggered by a regular ASP. NET Request.
Web service! = Soap and XML
One of the most important functions of ASP. Net Ajax is webmethods and page methods on the server that can call asynchronous XML-HTTP requests using browser clients. However, when I tell someone about this function, I feel a little scared.
Most of us will think of soap and XML when we hear the term "Web service. These two technologies are not mentioned in the same sentence for the sake of concise language. Yes, you can use ASP. NET ajax to call webmethods from JavaScript. But you are wrong. ASP. NET Ajax does not use soap or XML.
Figure 5 shows the data transmitted over the network when the web method call in Figure 4 is executed. In addition to the HTTP header, the only data transmitted in the request is the zip code entered by the user, and the only data returned in the response is a string representing the city and state. You will not see any soap or XML (or view status, in this case ). On the contrary, input and output are encoded using JavaScript Object Notation (JSON), which is much shorter and easier to process than XML. Requests and responses use a simple protocol instead of soap, which is basically HTTP. The combination of HTTP and JSON makes ASP. Net Ajax calls to webmethods and page methods much more effective than traditional Web service calls.
JSON is an emerging industry standard serialization format. It is also the native format used by ASP. NET Ajax. Microsoft Ajax library's SYS. serialization. javascriptserializer class supports JSON serialization and deserialization on the client. The system. Web. Script. serialization. javascriptserializer class supports JSON serialization and deserialization on the server.
Not all types are JSON compatible. For example, JSON cannot process objects with circular references. When you need to return complex data types that are not compatible with JSON, you can use the scriptmethod attribute of ASP. NET ajax to serialize the return type to XML. This technique is also useful for returning XML data, as shown below:
[ScriptMethod (ResponseFormat=ResponseFormat.Xml)]public XmlDocument GetData(){...}
In addition, you can build and register a custom JSON converter that allows serialization and deserialization of types that are generally not compatible with JSON. ASP. NET Ajax January futures CTP contains three such converters: one for dataset, one for datatable, and the other for datarow.