Thursday, March 21, 2019

Calling Server side method from Client Script ASP.Net

A way to call service from client browser without a post back. This is only a structure, this will receive call back request from client page (aspx) by implementing ICallbackEventHandler interface


Step 1: [new Class]
public partial class ClientCallbackPage : System.Web.UI.Page, ICallbackEventHandler

{


}

Step 2: [Interface implementation]
The ICallbackEventHandler has two methods method 1: RaiseCallBackEvent() that receives request from the client browser, accept param as string argrument, method 2: GetCallbackResult() return result back to client browser.

public void RaiseCallbackEvent(string callbackEventArgument)

{
//m_callbackEventArgument is a string variable declare in te class
m_callbackEventArgument = callbackEventArgument;
}

Step 3:[Interface implementation]

//method to execute server method and return result back
public string GetCallbackResult()
{
//type ur code here

return (something); //return value will send to the client script method
}

Step 4:

//Client script
function ClientCallbackScript(result, context)
{
//result will return the data from server.(see return (something); above)

//type ur code here
}

Step 5:

// in page load we are deciding for which event
//the server side method to invoke
if (! Page.IsPostBack)
{
string callbackEventReference =
Page.ClientScript.GetCallbackEventReference(this,
"parameter pass from client", "ClientCallbackScript",
"null");

txtName.Attributes["onclick"] = callbackEventReference;//event fire for each click in the text box
}

No comments: