Thursday, June 13, 2013

Call Server Side method from JavaScript



This query is asked many times on asp.net forums,
How to call Server Side methods or functions using JavaScript in ASP.Net?
So I am providing the best solution for this important question as below.

There is two ways for this solution.

1.     Using PageMethods through AJAX.

2.     IPostBackEventHandler .

I am explaining the same using ASP.Net AJAX PageMethods.

ASP.Net AJAX ScriptManager allows you to call Server Side ASP.net methods from client side without any PostBack using PageMethods. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.

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="ScriptManager1" runat="server" EnablePageMethods="true">

</asp:ScriptManager>


HTML Markup

<form id="form1" runat="server">

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

</asp:ScriptManager>

<div>

Your Company :

<asp:TextBox ID="txtName" runat="server" ></asp:TextBox>

<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()"/>

</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 ShowCurrentTime() {

PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);

}

function OnSuccess(response, userContext, methodName) {

alert(response);

}

</script>


Above the ShowCurrentTime method makes an AJAX call to the server using ASP.Net AJAX ScriptManager PageMethods and executes the GetCurrentTime method which accepts the Company Name and returns a string value.

Server Side Methods

C#

[System.Web.Services.WebMethod]

public static string GetCurrentTime(string Company)

{

return"Ashok" + Company+ Environment.NewLine + "The Current Time is: "

+ DateTime.Now.ToString();

}


The above method simply returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#) and also it is declared as Web Method unless you do this you won’t be able to call the methods using ASP.Net ScriptManager PageMethods.

Troubleshooting: ‘PageMethods Is 'Undefined'’ error

1.       Try setting EnablePageMethods="true" in the script manager tag


<asp:ScriptManager ID="ScriptManager1" runat="server"  EnablePageMethods="true"/>


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

If anyone has doubt then please let me know.

3 comments:

Ashok kumar said...

If this article is usefull then plz provide comments.

vimalendra said...

useful concepts. thank for it.

Unknown said...

nice information Ashok. useful for web developers....