Sunday, February 24, 2013

Calling Code behind Server function from Javascript

It is quite straight simple and I am using Asp.Net. The requirement and the procedures are as following.
It might be helpful if compare with Calling Web Services from Javascript .
1. Using Ajax
2. Set EnablePageMethods="true" in ScriptManager or ToolkitScriptManager attribute.
3. Code behind method must be public.
4. Apply WebMethod attribute to the codebehind function [System.Web.Services.WebMethod]
[System.Web.Services.WebMethod]

public static string GetContactName(string custid)

{
   //Do Logic staff here
   return "Result";
}
5. Create javascript function
(If javascript is external file, add ref in body tag. Not in head tag.)

function CallMe(custidTextBox,DestTextBox)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, DestTextBox);
 }
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
6. Attach this javascript to desired control.
<input id="BtnSave" class="button_sub" name='<%# Eval("Document_No") + "|"+ Eval("Line_No")%>' type="button" value="Save" onclick="SaveByMe(this,this)" /> 
That's it.
Enjoy Programming.  
Ref : http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

No comments:

Post a Comment