April 28, 2011

Using jQuery to Consume ASP.NET JSON Web Services

jQuery is nowadays a very effective for client side programming as it reduce code and increase the performance of any thing. Calling web service in asp.net using jQuery is very easy as you find a lot of codes on net some of them are so easy and some of them quite complex for the beginners.

First of all here you need to know the output format of web service to pass data to database or retrieve from database. Web Service returns output into two format.
  • XML
  • JSON
Its depend on you which format you like in your coding.

Check this code

Here's the final code which works fine on VS 2008/2010

--------------------------
ASPX MARKUP :
-------------------------------


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsonCall.aspx.cs"
      Inherits="Test_Web.JsonCall" %>

<!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>JSON Call</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">

        $(function() {

            $("#btnShow").click(function() {

                $.ajax(
                {
                    type: "POST",
                    url: "JsonService.asmx/GetNameById",
                    data: "{'Id':'" + $("#txtID").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data, status) {
                        $("#txtName").val(data.d);
                    },
                    error: function(mgs) {
                        alert(mgs.d);
                    }
                });
            });
        });
     
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="txtID" type="text" /><br />
        <input id="txtName" type="text" /><br />
        <input id="btnShow" type="button" value="Show" />
    </div>
    </form>
</body>
</html>

--------------------------
WEB SERVICE
--------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace Test_Web
{
    /// <summary>
    /// Summary description for JsonService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 JsonService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetNameById(int Id)
        {
            string returnString = "";

            if (Id == 1)
            {
                returnString = "Alpha";
            }
            else if (Id > 1 && Id <= 10)
            {
                returnString = "Beta";
            }
            else
            {
                returnString = "Gamma";
            }

            return returnString;
        }
    }
}

Web services are great tools that afford you substantial flexibility. It’s important not to overlook them. I believe that to be a short-sighted and counterproductive way to do things.