Tuesday, January 1, 2013

How to Call Server Side Method from Client Side

In the example we are going to write a method to get the current time as a server side method, make an AJAX call to the server and executes the GetCurrentTime method.

Below is our HTML markup. TextBox to enter name and a button to execute the call

Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />

Below is our client side code.

<script type="text/javascript">
function ShowCurrentTime() {
type: "POST", // Request type
url: "Jquery.aspx/GetCurrentTime", //Page URL/Method name
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', // parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,//success method
failure: function (response) {

function OnSuccess(response) {

Below is our server side code. Note that this method is declared as static and a WebMethod
public static string GetCurrentTime(string name)
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();

No comments:
Write comments
Recommended Posts × +