This article presents an example of how to consume a web service in an ASP.NET application using the jQuery.ajax() method. I have been developing applications running on web browsers for many years and I realize that AJAX and jQuery are getting close to the ultimate dreams of any programmer working on this subject for some time. jQuery is a client-side scripting library, so it is totally independent from the development environment, regardless of whether it is ASP.NET, J2EE, PHP, or any other platform. Visual Studio is readily available to me, so the example is created as an ASP.NET project.
- type: Specifies the type of request (GET or POST).
- url: Specifies the URL to send the request to. The default is the current page.
- contentType: The content type used when sending data to the server. The default is "application/x-www-form-urlencoded".
- dataType: The data type expected of the server response.
- data: Specifies data to be sent to the server.
- success(result,status,xhr): A function to be run when the request succeeds.
- error(xhr,status,error): A function to run if the request fails.
- $.ajax({name:value, name:value, ... }) //The parameters specifies one or more name/value pairs for the AJAX request.
Code
In the following example we will use ASP.NET to create a simple Web Service that converts the temperature from Fahrenheit to Celsius and vice versa. The structure of the attached Microsoft Visual Studio 2012 solution is as follows:
This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web Services. Here in the TempratureConverter .asmx Web Service I wrote two web methods for a sample application. One is FahrenheitToCelsius() that will convert the temperature from Fahrenheit to Celsius and another one is CelsiusToFahrenheit that will convert the temperature from Celsius to Fahrenheit.
Note : To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line [System.Web.Script.Services.ScriptService].
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
-
- namespace jQuery.AjaxWebServiceCall
- {
-
-
-
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
-
- [System.Web.Script.Services.ScriptService]
- public class TempratureConverter : System.Web.Services.WebService
- {
-
- [WebMethod]
- public string FahrenheitToCelsius(string fahrenheit)
- {
- return (((Convert.ToDouble(fahrenheit) - 32) / 9) * 5).ToString();
- }
-
- [WebMethod]
- public string CelsiusToFahrenheit(string celsius)
- {
- return (((Convert.ToDouble(celsius) * 9) / 5) + 32).ToString();
- }
- }
- }
This document is saved as an
.aspx file. In the HTML section of
Default.aspx, you can see that we only have a few functional visual components.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQuery.AjaxWebServiceCall._Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <link rel="stylesheet" type="text/css" href="Styles/mb-ui.css"/>
- <link rel="stylesheet" type="text/css" href="Styles/jquery-ui.css"/>
- <script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>
- <script type="text/javascript" src="Scripts/jquery-ui.js"></script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div id="MainDialog" title="Temperature Converter">
- <table width="100%">
- <tr>
- <td><label>Fahrenheit : </label></td>
- <td><asp:TextBox ID="txtFahrenheit1" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>
- </tr>
- <tr>
- <td><label>Celsius : </label></td>
- <td><asp:TextBox ID="txtCelsius1" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>
- </tr>
- <tr>
- <td colspan="2"><hr /></td>
- </tr>
- <tr>
- <td><label>Celsius : </label></td>
- <td><asp:TextBox ID="txtCelsius2" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>
- </tr>
- <tr>
- <td><label>Fahrenheit : </label></td>
- <td><asp:TextBox ID="txtFahrenheit2" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
This code shows how to call Web Service methods using a jQuery.ajax call. Here I am calling the Web Method on the TextBox Keyup event so as soon as the user enters data into the TextBox the keyup event is fired and due to the ajax call the result value will be displayed on the page.
- <script type="text/javascript">
- $('#' + '<%= txtFahrenheit1.ClientID%>').keyup(function () {
- if ($('#' + '<%= txtFahrenheit1.ClientID%>').val().length == 0) {
- $('#' + '<%= txtCelsius1.ClientID%>').val('');
- }
- $.ajax({
- type: "POST",
- url: "TempratureConverter.asmx/FahrenheitToCelsius",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- data: JSON.stringify({ 'fahrenheit': $('#' + '<%= txtFahrenheit1.ClientID%>').val() }),
- success: function (data) {
- $('#txtCelsius1').val(data.d);
- }
- });
- });
- $('#' + '<%= txtCelsius2.ClientID%>').keyup(function () {
- if ($('#' + '<%= txtCelsius2.ClientID%>').val().length == 0) {
- $('#' + '<%= txtFahrenheit2.ClientID%>').val('');
- }
- $.ajax({
- type: "POST",
- url: "TempratureConverter.asmx/CelsiusToFahrenheit",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- data: JSON.stringify({ 'celsius': $('#' + '<%= txtCelsius2.ClientID%>').val() }),
- success: function (data) {
- $('#txtFahrenheit2').val(data.d);
- }
- });
- });
- </script>
You can easily debug jQuery.ajax calls using Firebug in Firefox or Developer Tools in Internet Explorer. You can see the parameters being sent to the Web Service using the ajax call and the response from the Web Service and the time period between the request and the response.
References