AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1537&pId=-1
ICallback & JSON Based JavaScript Serialization
page
by Muhammad ADnan Amanullah
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 35473/ 34

Introduction

While working in ASP.NET, sometimes we need to call server side methods asynchronously without having a postback. Sometimes it is either a full page postback or partial page postback. But thanks to the ASP.NET team, we are provided implementation of ICallback very easily.

ICallback

ICallback is lightweight process. It uses well known XMLHTTP object internally to call server side method. It does not cause page postback and does not cause page rendering. If we are to show output at the client side, we need to make output HTML ourselves and render the controls manually.

ICallbackEventHandler

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

We just need to perform some action through server side code at server side. It then needs to return the results, but results are in instance or object of any class which would not be easy for JavaScript code to handle. Here we prefer JSON which stands for JavaScript Object Notation.

JSON

JSON is a lightweight, data-interchange format. ASP.NET gives good support for JSON as well. It is rapidly adopting because it is easy read by human and machine as well.

ICallback Server Side Implementation

Let us first implement ICallbackEventHandler to call the server side method asynchronously step-by-step

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

The following are the definition of two methods which we need to implement.

RaiseCallbackEvent method invoke through JavaScript function.

Listing 1

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

GetCallbackResult method invokes itself when the processing of RaiseCallbackEvent method is completed.

Listing 2

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 call/raise server side method which was RaiseCallbackEvent string eventArgument).

ReceiveServerData(arg, context) would get the result through arg parameter by GetCallbackResult().

Listing 3

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 + "; }";        
scriptMgr.RegisterClientScriptBlock(this.GetType(),"CallServer", callbackScript, true);
}

ICallback Client Side Implementation

Listing 4

<script language=javascript type=text/javascript>
function ReceiveServerData(arg, context)
{
  alert(arg); //just to show output
} 
function CallSrv()
{
  CallServer('get customer', '');
}
</script>
<input type="button" value="get customer" onclick="CallSrv()" />

That is it. These are the steps which you need to use to call and get results from the server side code using ICallback.

Now we will go ahead with some very easy steps for JSON based JavaScript serialization to return results in JavaScript's easily parseable format.

Suppose we have the following class whose object we need to return to JavaScript function through JavaScript serialization.

Sample Class:

Listing 5

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

JSON Code

Declare string jsonResult at the class level, which would be used to contain final results and returns.

After some sample code in both methods, the code will look like the following:

Listing 6

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;
}

Asynchronously output would be within a millisecond and without Postback.

Figure 1

Conclusion

Callback is a lightweight technique used to call server side methods asynchronously from JavaScript without any postback and reloading/rendering of unnecessary parts of page and unnecessary code.

So we can use that when we need to perform any operation at backend means at server, like update records in database, etc. You do not need to send all your contents of page in request and make that object heavyweight which could cause slow performance.

JSON is lightweight, data-interchange format to make server side class objects easily parseable by client side code to show output on a browser. I used JavaScript serialization technique to convert server side entity into client side entity to make it accessible/readable/useable at client side.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 2:13:52 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search