On my current project I wanted to add simple callback functionally. After searching google for a while and finding various solutions that I couldn’t get to work I came across the following posting from Microsoft:
Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages
It was very straight forward and I was able to get my callback going.
The following is the code behind that I used to get it working:
void Page_Load(object sender, EventArgs e) { PageCallbackSetup(); } /// <summary> /// Setup for the callback for a page /// </summary> private void PageCallbackSetup() { var cm = Page.ClientScript; // Client side function that will be executed when callback is finished var cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", ""); // Function that is called to start the callback to the server var callbackScript = "function CallServer(arg) {" + cbReference + "; }"; // Register script with the page for the callback cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true); } #region ICallbackEventHandler Members /// <summary> /// Returns result to client /// </summary> /// <returns>string of results from the server</returns> public string GetCallbackResult() { return "This is the time from the callback: " + DateTime.Now.ToString(); } /// <summary> /// Raised when the callback takes place /// </summary> public void RaiseCallbackEvent(string eventArgument) { } #endregion |
The following is the HTML markup:
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %> <!doctype html> <html lang="en"> <head runat="server"> <title></title> <script type="text/javascript"> function ReceiveServerData(arg) { MessageFromServer.innerText = arg; } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="Callback" onclick="CallServer('CallSubmittedFrom')" /> <br /> <span id="MessageFromServer"></span> </div> </form> </body> </html> |