public void RaiseCallbackEvent(string eventArgument)
{
}
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(
}
</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)
{
Customer customer = new Customer();
customer.Name = "Muhammad Adnan";
customer.Age = 24;
System.Web.Script.Serialization.JavaScriptSerializer jss;
jss =
new System.Web.Script.Serialization.JavaScriptSerializer();
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.
FYI: sample code is attached @ the end