3. Server-Side C# code (i.e. apsx.cs file)
public partial class Default2 : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler{private static Hashtable hashTable;protected String returnValue;protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){String cbReference =Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");String callbackScript;callbackScript = "function CallServer(arg, context)" +"{ " + cbReference + ";}";Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"CallServer", callbackScript, true);
hashTable = new Hashtable();hashTable.Add("Hawaii", "GMT -10:00");hashTable.Add("Central America", "GMT -06:00");hashTable.Add("Greenland", "GMT -03:00");hashTable.Add("Athens", "GMT +02:00");
DropDownList1.DataSource = hashTable;DropDownList1.DataTextField = "key"; //If you say value Values from HashTable will be added to DrpdownlistDropDownList1.DataBind();}}
In the above code, please note the following:
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");If we debug the code “cbReference” it will contain “WebForm_DoCallback('__Page',arg,ReceiveServerData,context,null,false)”; . Observe that the string, WebForm_DoCallback contains ReceiveServerData, it’s the javascript function we have written in step 2.
String callbackScript;callbackScript = "function CallServer(arg, context)" + "{ " + cbReference + ";}";Again “callbackScript” will contain some string. Actually it is a JavaScript function which we will register to the client page. Using
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"CallServer", callbackScript, true);This registers our CallServer function on the page. We are essentially passing the selected item of the Dropdown list to the CallServer function if you see the source code of the output page the CallServer function will appear as follows:
<script type="text/javascript"><!--function CallServer(arg, context){ WebForm_DoCallback('__Page',arg,ReceiveServerData,context,null,false);}// --></script>
This CallServer function is responsible for raising the callbackEvent ( i.e. RaiseCallbackEvent(String eventArgument) ) and the “arg” will be the eventArgument.
4. Finally add RaisecallbackEvent and GetCallbackResult.
Add following code to aspx.cs filepublic void RaiseCallbackEvent(String eventArgument){if (hashTable[eventArgument] == null){returnValue = "-1";}else{returnValue = hashTable[eventArgument].ToString();}}public String GetCallbackResult(){return returnValue;}
The above code provides the basic plumbing to implement asynchronous callbacks using ICALLBACKEventHandler. In subsequent articles we will extend this to real world applications and develop an AJAX-enabled GridView control.