Mar 24

The dataItems dictionary

Posted in ASP.NET MS AJAX      Comments Off on The dataItems dictionary

Today I noticed that there are still many guys that don”t know about the dataItems property which is exposed by the Sys.WebForms.PageRequestManager. So, I decided to write a small sample that will show you how to use it when you”re using partial updates and need to send some info back to the client during a partial postback.

So, here”s a really simple example which really doesn”t do anything but show how to use this property. Lets suppose that I need to send an object (which has two properties called Name and Date) from the server side to the client during a partial postback. There are several options for achieving this but the easiest is to use the dataItems property.

Lets start with a simple page:

<asp:ScriptManager ID=”manager” runat=”server” />
<asp:UpdatePanel runat=”server” ID=”panel”>
     <asp:Button runat=”server” ID=”bt” Text=”Get stuff” OnClick=”HandleClick” />

On the server side, all the action happens in the HandleClick method:

protected void HandleClick(Object sender, EventArgs e)
        if (!(IsPostBack && manager.IsInAsyncPostBack)) return;
        var obj = new { Name = “Luis”, Date = DateTime.Now };
        manager.RegisterDataItem(panel, new JavaScriptSerializer().Serialize(obj), true);


Thank god we have C# 3.0! Without it I”d have to write a dumb class just for demonstration purposes :,,) After checking if I”m in a partial postback, I”ll just go ahead and serialize my object and pass it to the RegisterDataItem method. Notice that I”m also passing the panel since it will be used as the key to index the data. Now I can show you the Javascript code that will recover those values:

<script type=”text/javascript”>
  function handleLoaded(sender, e){
    if( sender.get_isInAsyncPostBack() ){
      var aux = e.get_dataItems()[“<%= panel.ClientID %>”];
      alert( aux.Name + “:” + aux.Date );

As you can see, I need the client ID of the panel in order to retrieve the info I”ve just serialized in the server side. The cool thing about this is that I”m getting a JS object which has exactly the same properties as the object that was serialized in the server side. Notice also that I”m using the isInAsyncPostBack property to run my code only after running a partial postback (and I”m doing it from the pageLoaded event).

Ok, there might not be many scenarios where you”ll need this but this technique really shines when you need to get back more info during a partial postback.