jQuery is a
powerful JavaScript library that allows you to call ASP.NET page
method directly without any postback. You can call page method without
involving ScriptManager at all.
Creating page method:
First we have to create page method, it should be declared as static with the [WebMethod] attribute. Do you
have any question why page method should be declared as static? Because I had a
question and it had been answered by Dave ward. He has explained here.
Sample code:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
jQuery.ajax method:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/MethodName",
data: "{}",
dataType: "json",
success: function (msg) {
//do
something
}
});
Type:
The
type of request to make ("POST" or "GET")
URL:
A
string containing the URL to which the request is sent.
contentType: By default we have to use "application/x-www-form-urlencoded;
charset=UTF-8", When we sending data to server we have to use this content
type, which is fine for most cases.
Data: Data
send to be server, if data is not a string it’ll be converted to query string.
dataType: The type of data that you're expecting back from the server.
Success: A
function to be called if the request succeeds.
Source code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery AJAX call</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//
Add the page method call as an onclick handler for the div.
$('#btnGetTime').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetDate",
data: "{}",
dataType: "json",
success: function (msg) {
alert('Current Time is ' + msg.d);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnGetTime" value="Get Time" />
</div>
</form>
</body>
</html>
C#
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class _Default :
System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
[WebMethod]
public static string
GetDate()
{
return DateTime.Now.ToString();
}
}