In this article we will see how to call server side method or web services using JQuery. We will also see how to pass the value from client side to server side method without any web services or any other webpage.
This might be very useful when you want to call any server side function without given user feel of post back the web page you can use this trick to call server side method. Before JQuery we use to call server side function using Javascript. Actually JQuery library which is written using Javascript which will make the developers life easier.
All you need is JQuery library and can be download from JQuery website
Once you have downloaded the JQuery you can add the reference in you aspx page inside the
tag like this
Now lets create html button on our .aspx page. and one span tag to display the message got from server side. You can also take the ASP.Net server control button instead of html button control.
Lets see the JQuery function to get data from server side function
In the above JUqery function
URL: in this you have to pass the URL of the page and the method you want to call the function. you can also pass the web site URL in case you want to call web service using Jquery.
data: if you want to pass the value from server side you can do like this
data: "{'args':'Hello World'}"
if you dont want to pass any input value to the server function you can leave the data blank like this
data: "{}",
Now lets see the server side function which will return you the current datetime and this date time we will display in the client side in span tag
If you want to pass the value to the function you can declare the function with
NOTE: you have include attribute [System.Web.Services.WebMethod] to above the function which you want to call from JQuery
[System.Web.Services.WebMethod]
public static string CheckDateTime(string args)
{
return args +" Current Datetime is "+ DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss");
}
Now if you dont want any pass input parameter than see the server side function
[System.Web.Services.WebMethod]
public static string CheckDateTimeWithoutParameter()
{
return DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss");
}
Lets see the full HTML Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
Call server side method using Jquery
And Server side code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string CheckDateTime(string args)
{
return args +" Current Datetime is "+ DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss");
}
[System.Web.Services.WebMethod]
public static string CheckDateTimeWithoutParameter()
{
return DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss");
}
}
You can also download the above code by clicking below link