65.9K
CodeProject is changing. Read more.
Home

ICallbackEventHandler

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 11, 2013

CPOL
viewsIcon

9541

By using ICallbackEventHandler we can make asynchronous calls to server so that we can avoidpost back of the web page.Firstly we have to implement

By using ICallbackEventHandler we can make asynchronous calls to server so that we can avoid post back of the web page.

Firstly we have to implement the interface ICallbackEventHandler,
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
then we have to implement two methods in the interface ICallbackEventHandler,
  • GetCallbackResult
  • RaiseCallbackEvent
  #region ICallbackEventHandler Members

public string GetCallbackResult()
{return result;}
public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}

#endregion
Here for simplicity i am returning a static data.You can return dynamic data also.Then you need to Get Call back Event Reference through Page.ClientScript,
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
so now our class looks like this,
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
public string result;
protected void Page_Load(object sender, EventArgs e)
{
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
}

#region ICallbackEventHandler Members
public string GetCallbackResult()
{
return result;
}

public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}
#endregion
}
Now add one textbox and one HTML Button to the designer.For call back we should use HTML Button.In the onclick event of HTML Button call the javascript method GetValue();

Our Javascript code looks like,
  function GetValue()
{
CallBack();
}
function GetName(arg,context)
{
document.getElementById('txtPercentage').value=arg;
}
Build and Run the application.Now while clicking HTML Button the textbox is populated with the value from the server without posting the page.