2008-09-23

ASP.NET Ajax, JQuery & JSON Date Serialization

A little while back I came across a great post on how to use JQuery to do more efficient client side paging by Dave Ward. The sample shows you how to use JQuery to do Ajax callbacks for client side paging using a grid template. After downloading the demo and parsing through it all, I found a lot of things I really liked and even came across a little gotchya with the way ASP.NET serializes dates in JSON.

One part I really enjoyed about this sample is that your objects on the server are translated into client side objects. So Order.OrderID or Order.ShippingAddress.ShipName would work the same on the client and server side of the programming. The jtemplates add-in allows you to name your active object of the collection you are looping through a lot like .NET like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<tbody>
{#foreach $T.d as order}
<tr>
<td>
{$T.order.OrderID}
</td>
<td>
{$T.order.ShippingAddress.ShipName}
</td>
<td>
{DateDeserialize($T.order.OrderDate).format('MM/dd/yyyy')}
</td>
<td>
{DateDeserialize($T.order.RequiredDate).format('MM/dd/yyyy')}
</td>
<td>
{$T.order.ShippingAddress.ShipCountry}
</td>
</tr>
{#/for}
</tbody>

As you can see the order object is used in the jtemplates code just like in .NET code.

You may have noticed the DateDeserialize() function followed by the extension method .format() in the snipped above. This is due to some date deserialization issues I ran into. The signature for the DateDeserialize method is as so:

1
2
3
function DateDeserialize(dateStr) {
return eval('new' + dateStr.replace(/\//g, ' '));
}

This method is basically returning the evaluation of the date returned by the .NET framework (ex: /Date(894427200000)/), replacing the / with a space with the keyword "new" in front of it. This will return us a JavaScript Date object. Then I'm using the .format() extension method from the included MSAjax framework. It took me a little while to figure out, but once I did I fell in love. You can't put a price on full on object-oriented programming!

Special thanks to Dave Ward for opening my eyes to the power of JQuery!

Hope this helps!


comment: