ICallback and JSON-Based JavaScript Serialization

ICallback and JSON-Based JavaScript Serialization

When working in ASP.NET, sometimes you need to call server-side methods asynchronously without having either full-page or partial-page postback. Thanks go to the ASP.NET team to provide an easy implementation of ICALLBACK.

ICALLBACK

ICALLBACK is a lightweight process. It uses a well-known XMLHTTP object internally to a call server-side method. It doesn't cause page postback, so it doesn't cause page rendering. You show output at the client side, so you need to make the output in HTML yourself and render controls manually.

ICALLBACKEVENTHANDLER

ICALLBACK is implemented in ASP.NET by using the ICALLBACKEVENTHANDLER interface. This interface has two methods; one of them is used to call from JavaScript (client-side code) and other one returns the result asynchronously back to JavaScript function.

You just need to perform some action through server-side code at the server side; it needs to return results, but the results could be an instance or object of any class that would be not easy for JavaScript code to handle easily. So here, JSON, which stands for JavaScript Object Notation, is a better choice.

JSON

JSON is lightweight data-interchange format. ASP.NET gives good support for JSON as well. It's rapidly adopting JSON because it's lightweight and easy to read, both by humans and machines.

Callback Server-Side Code

First, implement ICALLBACKEVENTHANDLER to call a server-side method asynchronously, step by step.

Implement Server Side (C#) Page/Control class by System.Web.UI.ICallbackEventHandler

Following are definitions of two methods that must be implemented. The RaiseCallbackEvent method invokes by using a JavaScript function:

public void RaiseCallbackEvent(string eventArgument)
   {
   //to do code here
}

The GetCallbackResult method invokes itself when it has completed processing the RaiseCallbackEvent method.

public string GetCallbackResult()
   {
      return "";
   }

In Page_Load or Page_Init event

The following statements are used to register client-side methods. CallServer(arg, context), as the name implies, would use the call/raise server-side method that was the RaiseCallbackEvent string's eventArgument. ReceiveServerData(arg, context) would get its result through the arg parameter by GetCallbackResult().

protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager scriptMgr = Page.ClientScript;
String cbReference = scriptMgr.GetCallbackEventReference(this,
   "arg", "ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context)
   {" + cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),"CallServer",
   callbackScript, true);
}

Call Client-Side Code

<script language=javascript type=text/javascript>
function ReceiveServerData(arg, context)
{
   alert(arg);
}
function CallSrv()
{
   CallServer('get customer', '');
}
</script>

<input type="button" value="get customer" onclick="CallSrv()" />

That's it. These are the steps you need to use to call and get results from server-side code using ICALLBACK. Now, you will go ahead to some very easy steps for JSON-based JavaScript serialization to return results in JavaScript's easily parseable format.

Suppose you have the following class whose object needs to return a JavaScript function through JavaScript serialization.

Sample Class

public class Customer
{
   public string Name;
   public int Age;
}

JSON Code

declare string jsonResult;

At the class level, this would be used to contain the final result and return. After some sample code in both methods, the code will look like the following:

public void RaiseCallbackEvent(string eventArgument)
{
   //populate Customer object to return
   Customer customer = new Customer();
   customer.Name     = "Muhammad Adnan";
   customer.Age      = 24;

   //JavaScript serialization of Customer object
   System.Web.Script.Serialization.JavaScriptSerializer jss;
   jss =
      new System.Web.Script.Serialization.JavaScriptSerializer();

   //stringbuilder to contain serialized customer object
   System.Text.StringBuilder sbCustomer =
   new System.Text.StringBuilder();
   jss.Serialize(customer, sbCustomer);


   jsonResult = sbCustomer.ToString();
}

public string GetCallbackResult() 
{
   return jsonResult;
}

Asynchronous output would occur within a millisecond and without postback.

Conclusion

Callback is lightweight technique used to call server-side methods asynchronously from JavaScript without any postback and reloading/rendering of unnecessary parts the of page and unnecessary code. JSON is a lightweight data interchange format to make server-side class' objects easily parsable by client-side code to show output on the browser.



About the Author

Muhammad Adnan Amanullah

.Net Evangelist http://weblogs.asp.net/MuhammadAdnan http://realfantasy.wordpress.com http://interviewquestion.wordpress.com

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

  • Is your sales and operations planning helping or hurting your bottom line? Here are 5 useful tips from the experts at Quintiq to guide you to a better S&OP strategy.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds