We can run server side code from the client without performing a Postback using ICallBackEventHandler interface.The ICallbackEventHandler interface can be implemented on a page or a Web control. The interface contains two key methods: RaiseCallbackEvent(string EventArgs) and GetCallbackResult().
The message sent in the call back request from client is received by the RaiseCallbackEve(). It can be designed to parse the message and determine what server-side logic will be executed. Once the server-side code is finished, It uses the GetCallbackResult() method to create a string values to be sent to the client.
Lets create a simple example
To use ICallbackEventHandler, we will need to inherit it on the page.
- public void RaiseCallbackEvent(string eventArgument)
- public string GetCallbackResult()
- public string GetCallbackResult()
Method RaiseCallbackEvent gets called automatically whenever callback event is raised and GetCallbackResult returns the string value to client.
In page load event we have to create CallBackeventReference which will interact with client and server.
The class looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace MSCoderICallBackEventHandlerSample
{
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager scriptManager = Page.ClientScript;
String cbReference = scriptManager.GetCallbackEventReference(this, "returnValue", "GetResult", "context");
String callbackScript = "function CallServer(returnValue, context) {" + cbReference + "; }";
scriptManager.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
if (Page.IsCallback)
{
////IF any operation do it here.
}
}
#region ICallbackEventHandler Members
private string returnValue;
public string GetCallbackResult()
{
return returnValue;
}
public void RaiseCallbackEvent(string eventArgument)
{
returnValue = DateTime.Now.ToString();
}
#endregion
}
}
HTML of the example
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MSCoderICallBackEventHandlerSample._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ICallbackEventHandler Sample</title>
<script language="javascript" type="text/javascript">
function GetResult(returnValue, context) {
document.getElementById("txtDateTime").value = returnValue;
}
function SendRequest() {
CallServer();
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtDateTime" runat="server" Text="">
</asp:TextBox>
<asp:Button ID="btnDateTime" OnClientClick="return SendRequest()" runat="server"
Text="Get Server Date Time" />
</form>
</body>
</html>
0 Comment(s)