Using ASP.Net AJAX ScriptManager , you can call Server Side ASP.Net methods from client side without any PostBack using PageMethods.

Actually it serves as an AJAX call to the server but it allows us to call the method or function defined at server side.For this you have to add a scriptmanager tag and set the EnablePageMethods property as true.


Enabling PageMethods
The first thing you need to do is add a ASP.Net AJAX ScriptManager to the page and set its EnablePageMethods property to true as shown below
<asp:ScriptManager ID="myScriptManager" runat="server" 
EnablePageMethods="true">
</asp:ScriptManager>

HTML Markup
<form id="form1" runat="server">
<asp:ScriptManager ID="myScriptManager" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox>
<input id="btnGetMessage" type="button" value="Show Message" onclick="ShowMessage()"/>
</div>
</form>

As you noticed above I have added a textbox when user can enter his name and a HTML button that calls a JavaScript method to get the Current Time.
Client Side Methods
<script type="text/javascript">
function ShowMessage() {
PageMethods.CallServerSideMethod(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>

Above the ShowMessagemethod makes an AJAX call to the server using ASP.Net AJAX ScriptManager PageMethods and executes the CallServerSideMethod method which accepts string parameter (name) and returns a string value.
Server Side Methods
C#
[System.Web.Services.WebMethod]
public staticstring CallServerSideMethod(string name)
{
return "Hello " + name + Environment.NewLine + "You have called server side method";
}

The above method simply returns a message. An important thing to note is that the method is declared as static (C#)  and also it is declared as Web Method.

Unless we mark this  method as with [System.Web.Services.WebMethod] attribute we  will not be able to call it using javascript function and ASP.Net ScriptManager PageMethods.

2 comments:

 
Top