Serializing Objects To JSON To Preload Ajax Data

I’ve been developing a large application with ASP.Net Ajax and ExtJS. It all works great together and in fact ASP.Net is just a easy way to access my .Net code/web services because the whole UI done with ExtJS constructed/controlled by javascript/Ajax.

When it comes to a 100% javascript UI there are some cases where you’ll load the javascript libraries just to do one or more AJAX calls before data is actually shown to the user. Still, you usually need the same Ajax calls later on to refresh some parts of the UI. I  went to think and search for a nice and easy way to preload some data and avoid those “load-time” Ajax calls.

To begin with, I always like to keep the number of javascript function to the minimum possible, so I implemented this function:

function updateModules(data, userContext, methodName) {
	if (data) {
		// do whatever you need with the data
	} else {
		// Do ajax call
		PageMethods.GetModules(updateModules, errorHandler);

That allows the function to act with 3 different behaviours:

// Will invoke the Ajax call

// Will skip the Ajax call and process the data right away

// This is the handler for a successful ASP.Net Ajax call
updateModules(data, context, methodName);

With this function I’ve pretty much every possible usage scenario covered, so all that was missing was a way to preload the data in the first request. This can be handled natively by ASP.Net by serializing the “GetModules” method response on the server side. On top of it, ASP.Net allows you to register a script block entirely from the “C#” side. So, I simply needed to add this to my Page_Load event:

using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e) {
	Page.ClientScript.RegisterClientScriptBlock(GetType(), "preloadedModules", "updateModules(" +
		(new JavaScriptSerializer()).Serialize(GetModules()) + ");"
		, true);

Alternatively you could also assign it to a variable and use it when ready.

In the end, my page will get loaded a lot faster not only because it didn’t have to process multiple Ajax requests but because the ASP.Net engine would have to initialize  a lot of code before processing and serializing that method’s returned object. This little optimization trick can even save more load time if you’ve several Ajax calls beeing done when the page loads.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Tags: , ,

One Response to “Serializing Objects To JSON To Preload Ajax Data”

  1. […] See the rest here: Serializing Objects To JSON To Preload Ajax Data « Alexandre Gomes […]

Leave a Reply

For spam filtering purposes, please copy the number 5977 to the field below: