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

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

  • Managing your company's financials is the backbone of your business and is vital to the long-term health and viability of your company. To continue applying the necessary financial rigor to support rapid growth, the accounting department needs the right tools to most efficiently do their job. Read this white paper to understand the 10 essentials of a complete financial management system and how the right solution can help you keep up with the rapidly changing business world.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds