Skip navigation

Gain Control of Partial Rendering with Data Items

Pack Custom Data in UpdatePanel’s Payloads





Gain Control of Partial Rendering with Data Items

Pack Custom Data in UpdatePanel s Payloads


By Dino Esposito


Partial rendering is what makes ASP.NET AJAX unique in the arena of frameworks for AJAX development. AJAX represents a paradigm shift for Web developers; partial rendering does the trick of letting developers use the same model they re used to that is, classic ASP.NET but in the context of AJAX applications. With partial rendering, your page keeps on working through postbacks and viewstate, but bypasses the browser whenever a form submission occurs. Instead of going through a regular SUBMIT, your page will use XMLHttpRequest, thus circumventing a full refresh.


The UpdatePanel control is the nerve center of partial rendering. Each chunk of markup wrapped up in the body of an UpdatePanel control is refreshed independently from the remainder of the page. To transform a regular ASP.NET page in an ASP.NET AJAX page, you simply partition the body of the page in an array of updatable regions, including nested regions. Next, using triggers and other properties, you set the rules that govern the refresh of the regions.


However, not all pages lend themselves to be divided in a set of small updatable regions. Unfortunately, not in all cases can you reasonably think of having an individual region for each portion of markup that must be independently updated. In general, one could always design a new page to fulfill this requirement, but here you are addressing existing pages, with their own fixed layout and their largely hard-coded logic. One of the key benefits of partial rendering is the speed of AJAXification and the limited impact on existing pages. So what s the issue?


Suppose you have wrapped your entire page markup in updatable regions. What if the update of a region may trigger the update on another region, or even on one control in another region? What if you realize that you need to update one control that is not contained in an updatable region? And what if the logical update requires some work on the client?


Similar issues were raised early in the review process of ASP.NET AJAX, which lead to the introduction of a particular method in the ScriptManager class, the RegisterDataItem method. While I can t say that this method is for common use, it certainly makes it possible for developers of AJAX pages and controls to add features that otherwise would be impractical with the standard set of partial rendering functionalities.


The RegisterDataItem Method

Defined in the ScriptManager class, the RegisterDataItem method sets a server-generated string that will be added to the response of the ongoing partial rendering update. This string is appended to the standard response and is extracted and processed by the client-side AJAX framework. Here are the signature and implementation of the method (by the way, you can access the full source code of the ASP.NET AJAX Extensions version 1.0 from


public void RegisterDataItem(Control control,

   string dataItem, bool isJsonSerialized)



      dataItem, isJsonSerialized);



The first argument indicates on behalf of which component (page or server control) the data is being registered. The second argument indicates the string to append. Finally, the third argument is a Boolean value that indicates whether the string is JSON-encoded text or simply plain text.


It is interesting to notice that the ScriptManager s method simply cascades to a similar, but static, method on the PageRequestManager internal class. This method simply checks whether there s an AJAX postback operation going on, then adds the specified string to an internal collection to be flushed to the response stream during the rendering stage.


The client framework of ASP.NET AJAX also features a page request manager class, specifically named Sys.WebForms.PageRequestManager. You should be able to see the symmetry. The server-side PageRequestManager prepares the data for sending and the client-side PageRequestManager gives client code a chance to retrieve it and process via JavaScript. I ll return to this and other programming aspects in a moment. For now, let me illustrate the motivation for additional data items with a concrete example excerpted from the same ASP.NET AJAX Extensions source code.


Data Items and the Timer Control

The System.Web.UI.Timer control is one of the few new server controls introduced by ASP.NET AJAX Extensions. It generates the script code that sets up a client timer and binds it to some code that performs a postback whenever the timer expires:


          Interval="10000" OnTick="Timer1_Tick"

          EnableViewState="False" />


On the server, a Tick event is fired whenever the timer expires; based on the preceding code snippet, a postback occurs every 10 seconds and will be processed through the Timer1_Tick method:


protected void Timer1_Tick(object sender, EventArgs e)


   // Code to run every interval



The Interval property sets the interval of the timer in milliseconds; the Enabled property starts and stops the timer. The Timer control uses the data items feature internally to reflect any new values assigned on the server to the Interval and Enabled properties.


As you can guess, the data items feature proves helpful when a given functionality is implemented in both the server and the client, and changes that occurred on the server must be reflected on the client. Partial rendering does a good job reflecting on the client any changes that occurred to the markup on the server. But when you need to apply the same pattern to raw data properties, you need data items in addition to partial rendering. The Timer control has no markup, but still needs to keep its client and server state in sync. Let s dig out the source code of the control. In the pre-render event handler, the Timer control does the following:


protected override void OnPreRender(EventArgs e)



    if (this._stateDirty && this.ScriptManager.IsInAsyncPostBack)


     this._stateDirty = false;


         this.GetJsonState(), true);





The control first checks whether it is engaged in an AJAX postback and whether its internal state has been modified. If so, it resets the flag of the state change and registers a data item in the form of a JSON string. As mentioned, this string the output of the internal GetJsonState function will be appended to the response and further processed on the client. That s all that a page or a control needs to do to forward extra and custom information to the client during a partial rendering operation.


You have no constraints as far as the format of the data item is concerned. It s entirely up to you and, as a page or control developer, you re responsible for both serialization and deserialization. However, the ASP.NET AJAX framework provides some JSON facilities. Let s see what the Timer control does:


private string GetJsonState()


   return ("[" + (this.Enabled ? "true" : "false") + "," +

           this.Interval.ToString() + "]");



The control returns a string like the following:



More importantly, it marks it as a JSON string. It is the JSON representation of a two-element array, and it will be deserialized to a JavaScript object on the client using the eval function. From a logical standpoint, the Timer control serves up an array with the current server-side values of two of its properties, Enabled and Interval. These two properties form the server-side state of the control. To grasp the importance and usefulness of the data items feature, you need to understand why the Timer control needs to push this data to the client.


As mentioned, the Timer control posts back automatically whenever the interval expires. The control is, in essence, an instance of the browser s timer object managed through the setTimeout method of the browser s window object. A client timer is not natively a tool to run a piece of code every n milliseconds until it is stopped. More simply, it is a tool that waits the specified number of milliseconds before executing once. After that, the timer is gone. It is in stand-by mode, but is no longer triggering the associated code. To reiterate the associated code, you need to repeatedly re-enable the timer. In doing so, you could vary the interval. Because the Timer control is hard-coded to do a postback whenever it expires, only the server code may change the value of the Interval and Enabled properties. If any of these properties is changed during a regular postback, there s no problem: an updated script will be uploaded for the timer as part of the new page. But what about partial rendering postbacks?


In this case, the data items feature allows the control to push to the client the delta of its state so that already downloaded client script can update the timer object. The Timer control, as well as most AJAX controls, downloads a script file with its client-side object model. Inside this code you ll find the function to post process the data items (see the file microsoftajax.timer.js).


A Quick Example

I struggled enough with the task of finding a great example for using RegisterDataItem. All in all, I still believe that the best example is the Timer control. RegisterDataItem is helpful when the following conditions are met:

  • Need to push server-generated data to the client.
  • Need to further process this data on the client to sync up the user interface with the application s state.


There are many scenarios where you need to push server data to the client; but not that many that require you to further process the data on the client. In most cases, you can push ready-to-display data, thus zeroing the work required on the client. Look at Figure 1. RegisterDataItem is really necessary when the amount of client script is nonzero; all things considered, it represents the most efficient way of accomplishing that task. This is definitely true for the timer example.


Figure 1: Schema for using RegisterDataItem.


Let s consider another example. Predictive fetch is one of the most important AJAX patterns because it provides guidance on how to make the browser more responsive by anticipating user actions and calls the server in advance. Imagine a page that provides a list of customers. When users select a customer, the page promptly shows all customer details. You can quickly code this through partial rendering using a DropDownList, a DetailsView, and a couple of ObjectDataSource controls. A user that selects a customer will likely need to see orders, as well. If you retrieve orders along with customer details, you keep the page s user interface frozen, and the Web server busy, for too long. You could, for example, serve users the customer details and upload the customer ID as a separate piece of information. A related script will take that information and place a separate and asynchronous call to get orders. Figure 2 shows an instance of the predictive fetch pattern.



























                 DataSourceID="CustomerViewDataSource" />











         PropertyName="SelectedValue" />



Figure 2: The markup of a predictive fetch page.


Processing Data Items on the Client

Registered data items are passed to the client infrastructure of ASP.NET AJAX through the dataItems property of the event data for the pageLoading, pageLoaded, and endRequest events. The dataItems property is a key/value dictionary where the key is the ID of the control that references the data or __Page if the referrer is the ASP.NET page. Here s how the sample page specifies its data in the pre-render event:


if (isDirty && ScriptManager1.IsInAsyncPostBack)



         CustomerList.SelectedValue, false);

    isDirty = false;



In this case, you re passing a plain string. Multiple pieces of data can be packed together using a JSON-encoded array. The next script shows how to retrieve this data at the end of a partial rendering operation:


function pageLoad()


  var manager = Sys.WebForms.PageRequestManager.getInstance();



function OnEndRequest(sender, args)


  var customerID = args.get_dataItems()["__Page"];

  if (customerID)







If dataItems returns an array, you then pick up the various elements using the familiar syntax of arrays:


var items = args.get_dataItems()["__Page"];

var item1 = items[0];


In this particular example, the preFetchOrdersForCustomer function will use the ID to fire an async call to a Web service to obtain the list of orders (see Figure 3). Two calls are made to the server, but they work asynchronously, which is good for the user and the system.


Figure 3: Data items used to fetch orders in advance.


The sample code accompanying this article is available for download.


Dino Esposito is a mentor with Solid Quality Mentors ( and specializes mainly in ASP.NET and AJAX solutions. He s the author of Introducing Microsoft ASP.NET AJAX (Microsoft Press, May 2007) and wrote the two volumes of Programming Microsoft ASP.NET 2.0, also for Microsoft Press. Late-breaking news is available at




Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.