Moving forward, we will see how to use jQuery Ajax
methods to call a WebService method in ASP.Net.
Integrating jQuery in ASP.Net
CodeDigest.Com has some useful FAQ’s to integrate jQuery
in asp.net projects.
Download
the latest jQuery library from jQuery.com and integrate into your project.
Read the following FAQ's to integrate jQuery library to your project.
What is jQuery? How to use it in ASP.Net
Pages?
How to enable jQuery intellisense in Visual Studio
2008?
How to use jQuery intellisense in an external javascript
file?
Creating Webservice
Now, to make our understanding simple we will include a
simple webservice method that returns date and time of the server. We will then
try consuming this webservice method using jQuery library. Include a webservice
in your project by right clicking the project in Solution Explorer and click
“Add New Item..” dialog box. Select Webservice from the dialog and name it as
GetDate.asmx.
Include a method called GetDateTime() that returns a
date time string .
In order to call the webservice method from javascript,
you have to uncomment the attribute
System.Web.Script.Services.ScriptService of webservice class. Refer the
below code[bolded]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script,
using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetDate : System.Web.Services.WebService {
public GetDate () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string GetDateTime()
{
return DateTime.Now.ToString();
}
}
Now, before consuming webservice method using jQuery it
is necessary to know some restrictions on calling webservice methods from
javascript.
1. Only POST method can be used to call a webservice
method.
2. The HTTP Content-Type header should be set to the
value “application/json”.
There is a built in validation layer in ASP.Net that
checks for the above 2 things. The request will be rejected if both the
constraints are not met. This is done for preventing some security
vulnerabilities like cross site request forgery attacks. Read the links in
Reference section to know more.
Consuming Webservice using jQuery
The below jQuery code can be used to call the webservice
method.
<script src="_script/jquery-1[1].3.2.js"
type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
$("#btGetDate").click(function() {
$.ajax({
type: "POST",
url: "/AjaxSample/GetDate.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#dvDate").html(msg.d);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="dvDate"></div><input id="btGetDate"
type="button" value="Get Date" />
</div>
</form>
</body>
|