Total Pageviews

6/05/2013

Using JQuery, AJAX, JSON and ASP.NET Web Services


We are on era of the web development where more and more websites are loading lots of dynamic content on web pages. In this tutorial, I will show how to use web service and JSON to display dynamic contents on web page. 

Create a new ASP.NET website in the visual studio and add following Product.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Product class objects to the clients.
           public class Product
         {
                   public int Id { get; set; }
                   public string Name { get; set; }
                   public decimal Price { get; set; }
         }
Next, add an ASP.NET web service ProductWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:
          [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 ProductWebService : System.Web.Services.WebService
       {
           List<Product> list = new List<Product>();
           
           public ProductWebService () 
           {
             //Uncomment the following line if using designed components
             //InitializeComponent();
              list.Add(new Product { Id = 1, Name = "TV", Price = 22000 });
             list.Add(new Product { Id = 2, Name = "Microwave", Price = 24000 });
             list.Add(new Product { Id = 3, Name = "WashingMachine", Price = 28000 });
             list.Add(new Product { Id = 4, Name = "Music Player", Price = 29000 });
             list.Add(new Product { Id = 5, Name = "Food Processor", Price = 19000 });
          
           [WebMethod]
           public List<Product> GetAllProducts()
           { 
             return list;
           }

           [WebMethod]
           public Product GetProductDetails(string productId)
           {
             int prodId = Int32.Parse(productId);
             Product product = list.Single(e => e.Id == prodId);
             return product;
           }
       }
In start, the web service declares a list of Product objects which I will be using to store Product objects for this tutorial. I have added five Product objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.
           List list = new List();
          list.Add(new Product { Id = 1, Name = "TV", Price = 22000 });
      list.Add(new Product { Id = 2, Name = "Microwave", Price = 24000 });
      list.Add(new Product { Id = 3, Name = "WashingMachine", Price = 28000 });
      list.Add(new Product { Id = 4, Name = "Music Player", Price = 29000 });
      list.Add(new Product { Id = 5, Name = "Food Processor", Price = 19000 });

A web method GetAllProducts returns the list of products to the clients.
          [WebMethod]
      public List<Product> GetAllProducts()
      { 
           return list;
      }

Another simple web method GetProductDetails will filter and return a single Product object based on product id.

           [WebMethod]
       public Product GetProductDetails(string productId)
       {
           int prodId = Int32.Parse(productId);
           Product product = list.Single(e => e.Id == prodId);
           return product;
       }

Next add the following code in your web page in HTML source. It has a DropDownList to display all products and an HTML table to display single product details.
 
    <form id="form1" runat="server">
    Select Product:
    <asp:DropDownList ID="DropDownList1" runat="server" Width="150">
        <asp:ListItem Text="Select" Value="-1" />
    </asp:DropDownList>
    <br />
    <br />
    <table style="border: solid 1px black; width: 300px; display: none;
    background-color:#f3f3f3"
        cellpadding="4" cellspacing="0" id="outputTable">
        <tr>
            <td>Product ID:</td>
            <td><span id="spnProductId" /></td>
        </tr>
        <tr>
            <td>Product Name:</td>
            <td><span id="spnProductName" /></td>
        </tr>
        <tr>
            <td>Price:</td>
            <td><span id="spnPrice" /></td>
        </tr>
    </table>
    </form>


Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
    <script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllProducts which is declared just after ready function. This function will call GetAllProducts web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from the DropDownList using JQuery val method and then pass that employee id to another JavaScript function GetProductDetails which will retrieve details of that particular employee by calling web service GetProductDetails method and then will display details in HTML table.

   <script type="text/javascript">

        $(document).ready(function ()

        {
            // Load Products
            GetAllProducts();

            var DropDownList1 = $("#DropDownList1");


            DropDownList1.change(function (e)

            {
                var productId = DropDownList1.val();
                if (productId != -1)
                {
                    // Get Product Details
                    GetProductDetails(productId);
                }
                else
                {
                    $("#outputTable").hide();
                }
            });

        });


        function GetAllProducts()

        {
            var DropDownList1 = $("#DropDownList1");

            $.ajax({

                type: "POST",
                url: "ProductWebService.asmx/GetAllProducts",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response)
                {
                    var Products = response.d;
                    $.each(Products, function (index, Products)
                    {
                        DropDownList1.append('<option value="' + Products.Id + '">' + Products.Name + '</option>');
                    });
                },
                failure: function (msg)
                {
                    alert(msg);
                }
            });
        }

        function GetProductDetails(productId)

        {
            $.ajax({
                type: "POST",
                url: "ProductWebService.asmx/GetProductDetails",
                data: "{'productId':'" + productId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response)
                {
                    var Product = response.d;
                    $("#spnProductId").html(Product.Id);
                    $("#spnProductName").html(Product.Name);
                    $("#spnPrice").html(Product.Price);
                    $("#outputTable").show();
                },
                failure: function (msg)
                {
                    alert(msg);
                }
            });
        }
    
    </script>
      

1. Function : GetAllProducts() In the above function, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the products. I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all products. If you will build and test your page in the browser you will see DropDownList populate with prodcut names as shown in the following figure. You can also see the JSON response in FireBug just below to the DropDownList. 

2. Function : GetProductDetails() The above function required for the GetProductDetails function. The code is almost similar to the GetAllProducts function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing product id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate product as there is only one product to receive from the web service method. Note the Product class properties Id, Name and Price are used to display values inside span elements declared in HTML table above. That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see efficient output.


So thats it you are ready to rock with JSON + Web Service



12 comments:

Unknown said...

Use web API to enjoy RESTful services. On the client side use knockoutjs for mvvm. You could reuse most of your js code, but you will notice that your code becomes cleaner instead of having scattered code all over. You will also enjoy knockout binding.

Anonymous said...

JavaScript functions will simply related to this top content.Functions referring with jquery will enable to obtain the real project issue. Jquery AJAX code makes sure makes sure you have JQuery file available
in the script folder of your website and the reference page of element will be added. Learn more about JQuery by visiting our link:

http://www.thinkittraining.in/java-script-and--jquery

for ict 99 said...
This comment has been removed by a blog administrator.
rated writer for you! – work 4 me said...

The downloading a certain content requires the implementation of the main project objectives on web pages. The customers should get the optimal set of the products.

Unknown said...

This is the best place where we can get good collection of information with very useful stuff, thanks very much for sharing the valuable information here...
Best Online Software Training Institute | Asp.Net Training

DeepikaOrange said...

Thanks for making me this article. You have done a great job by sharing this content in here. Keep writing article like this.

Node JS Training

application essay said...

In this lesson you have shown us a lot of different information that still needs to be well understood for further training.

Durga IT Solutions said...
This comment has been removed by the author.
Julia Loi said...

Great post I must say and thanks for the information. Education is definitely a sticky subject. it is still among the leading topics of our time. I appreciate your post and looking for more.
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg
mobile phone repair in Fredericksburg

Swetha K said...

t is a very helpful data. It will help to improve my knowledge about this topic. Thank you for this awesome post.
Pega Training in Chennai
Pega Course in Chennai
Primavera Training in Chennai
Full Stack Developer Course in Chennai
Corporate Training in Chennai

Renuraj said...

Great blog and Keep doing...!
selenium with java training
Selenium with c# training
Selenium with java course
Selenium with python Training

vé máy bay từ canada về việt nam said...

Đặt vé tại phòng vé Aivivu, tham khảo

vé máy bay đi Mỹ bao nhiêu

từ mỹ về việt nam được chưa

chuyến bay từ đức về hà nội hôm nay

vé máy bay nga về việt nam

giá vé máy bay từ anh về việt nam

mua vé máy bay giá rẻ từ pháp về việt nam

giá khách sạn cách ly

Chuyen bay cho chuyen gia nuoc ngoai

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews