Calling server side (cs file) method from client side through Page Method in asp.net C# (CSharp)
// .Aspx Coding //
<script type="text/javascript">
function
CallMe(src,dest) {
// call
server side method
PageMethods.GetContactName(ctrl.value,CallSuccess,CallFailed,
dest);
}
// 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());
}
</script>
// Add
Ajax Script Manager in form
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
// .CS Coding //
[System.Web.Services.WebMethod]
public
static string
GetContactName(string custid)
{
if
(custid == null || custid.Length == 0)
Return
String.Empty;
// Make
Database connection and return a specific value
Return custid;
}
// Write
On Page Load Event
If
(!Page.IsPostBack)
{
txtId1.Attributes.Add("onblur", "javascript:CallMe('"
+ txtId1.ClientID + "', '" +
txtContact1.ClientID + "')");
txtId2.Attributes.Add("onblur", "javascript:CallMe('"
+ txtId2.ClientID + "', '" +
txtContact2.ClientID + "')");
}
// .Aspx Coding //
<script language="javascript" type="text/javascript">
function
CalcSum() {
var
firstNo = document.getElementById("<%=
txtFirstNo.ClientID %>").value;
var
secondNo = document.getElementById("<%=
txtSecNo.ClientID %>").value;
if
(firstNo != '' && secondNo != '') {
PageMethods.getSum(firstNo,
secondNo, FillSumBox);
}
}
// Call
on Succeed
// set
the return value from server side to destination textbox value
function
FillSumBox(val) {
document.getElementById("<%= txtSum.ClientID %>").value =
val;
}
</script>
// Add
Ajax Script Manager in form
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<input id="btnSum" type="button" onclick="CalcSum()" value="Calculate Sum" />
// .CS Coding //
[System.Web.Services.WebMethod]
public
static int
getSum(int num1, int
num2)
{
return
(num1 + num2);
}