Lets go straight to an example and get it working.
1)Create a web application in VS 2008
2)In Page Load of "Default.aspx.cs" , enter the following code
/*Client function to Receive Server Data*/
string strReceiveServerData = "function ReceiveServerData(arg,context){RecieveServerDate2(arg);}";
/*Get Callback Reference*/
string strReceiveCallReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", strReceiveServerData);
/*Client function to Call Server... the reference of "Receive server data" function is added here*/
string strCallTheServer = "function CallServer(arg,context){" + strReceiveCallReference + ";}";
/*Register the script*/
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", strCallTheServer, true);
3) Inherit interface “ICallbackEventHandler” in page
public partial class AsyncServerCall : System.Web.UI.Page,ICallbackEventHandler
4) Add method code for interface "ICallbackEventHandler" in "Default.aspx.cs"
#region ICallbackEventHandler Members
string strVar = "";
public string GetCallbackResult()
{
return strVar;
}
public void RaiseCallbackEvent(string eventArgument)
{
strVar = "Hello World," + eventArgument;
}
#endregion
string strVar = "";
public string GetCallbackResult()
{
return strVar;
}
public void RaiseCallbackEvent(string eventArgument)
{
strVar = "Hello World," + eventArgument;
}
#endregion
5) Add below Javascript to aspx page. Make sure you add "script" tags.
<script>
function RecieveServerDate2(arg) {
alert(arg);
}
</script>
function RecieveServerDate2(arg) {
alert(arg);
}
</script>
6) And the final step... call the javascript function to make server call in body onload
<body onload=" CallServer('Guys', '');" >
Run it! And you will get an alert “Hello World, Guys”. Wasn’t the callback easy in ASP.NET?
No comments:
Post a Comment