Call CSharp Method by JavaScript in ASP.NETIntroduction
In this article i am explaining how to call a c# method using a JavaScript method. In the following example i simply input your name and concatenate Hello using c# method and that c# method is called using javascript method.
Code
1. First we create a page with one text box and one button as follow:
Client Callback
In above code on button click we call javascript GetMessage Method that in turn call UseCallback method.
2. Server side code
For this we have to implement IcallbackEventHandler interface. The interface requires to implement the RaiseCallbackEvent and the GetCallbackResult menthods, both of which work with the client script request. RaiseCallvackEvent enables us to do the work of retrieving the value from the page and do the operation whaterver we want and GetCallbackResult returns the result.
In Page_Load event we include the creation and placement of the client callback script manager i.e. Page.ClientScript.GetCallbackEventReference this function will manage the requests and response and put to the web page using the Page.ClientScript.RegisterClientScriptBlock.
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
private string _callbackResult = null;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.Request.Browser.SupportsXmlHttp)
{
string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetMessageFromServer", "context");
string cbScript = "function UseCallback(arg, context)" +
"{" + cbReference + ";" + "}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbScript, true);
}
}
#region ICallbackEventHandler Members
public void RaiseCallbackEvent(string eventArg)
{
_callbackResult = "Hello " + eventArg;
}
public string GetCallbackResult()
{
return _callbackResult;
}
#endregion
}