Showing posts with label calling server side method from javascript. Show all posts
Showing posts with label calling server side method from javascript. Show all posts

Tuesday, May 27, 2008

Calling server side method through javascript Using Asp.net

this is a small example, it will call a server method without having the expense of postback

//step 1: Inherit ICallbackEventHandler interface in your form

public partial class FormCallServer: System.Web.UI.UserControl, ICallbackEventHandler
string m_callbackEventArgument = "";

//step 2:
protected void Page_Load(object sender, EventArgs e)
{

string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this,
"document.getElementById('TextBox1').value ",
"ClientCallbackScript","null");

TextBox1.Attributes.Add("onChange", "javascript:" + callbackEventReference ); }

//step 3: Interface require to implement 2 monthods RaiseCallbackEvent and
//GetCallbackResult. These are predefined methods RaiseCallbackEvent initialise and
//GetCallbackResult will execute and return the output to called client method.

//below method is automatically called from client method
//notice parameter callbackEventArgument, it is an passed from client method, by this example it will be TextBox1.value (see which is mensioned above)

public void RaiseCallbackEvent(string callbackEventArgument)
{
m_callbackEventArgument = callbackEventArgument;
}

//below the main method for callback server method
public string GetCallbackResult()
{
//Your codes

return [you must return a string value]; //After executing this method it will below
//javascript function ClientCallbackScript
}

----------------------------------------------------------------------------
//step 4: you need some coding in client side also
//Argument result is the return value, after executing above GetCallbackResult

<Script type="text/javascript" >
function ClientCallbackScript(result)
{
//your code here
//a sample code from my side
document.getElementById('txtMyTestbox').value = result;
}

</Script >