call Server Side function from Client Side Code in ASP.NET

Some times we require to call server side method from client side. Here it is done using script manager.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >

<script type="text/javascript">
function callServer()
// call server side method
//Server side function get the 1 arguments i. We are passing $get('txtNo').value
//for that. CallSuccess is callback function for complete successfully.
//CallFailed is callback function on error. $get('divDest') is destCtrl parameter.
//If server side code executed successfully then CallSuccess will call.
//If server side code do not executed successfully then CallFailed will call.
PageMethods.ServerMethod($get('txtNo').value, CallSuccess, CallFailed, $get('divDest'));

// set the destination textbox value with the ContactName
function CallSuccess(res, destCtrl)
destCtrl.innerHTML = res;

// alert message on some failure
function CallFailed(res, destCtrl)
<input type="text" id="txtNo" />
<input type="button" id="test" value="Test" onclick="callServer();" />
<div id="divDest">

In .cs file

<WebMethod()> _
Public Shared Function ServerMethod(ByVal i As Integer) As String
If (i = 0) Then
Return "This is Zero"
Return "This is " & i
End If
End Function

Troubleshooting: ‘PageMethods Is 'Undefined'’ error

1. Try setting EnablePageMethods="true" in the script manager tag
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
2. Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.

<script type="text/javascript" language="javascript" src="script.js"> </script>
<form id="form1" runat="server">

3. Page methods needs to be static in code behind.

No comments:

Post a Comment