Click here to Skip to main content
Click here to Skip to main content

Consuming Webservice using JQuery ASP.NET Application

By , 18 Mar 2010
 

Introduction

jQuery is a JavaScript library with rich API to manipulate DOM, event handling, animation and Ajax interactions. The following are the essential features of jQuery that makes it so appealing for client side scripting.

  1. jQuery is Cross-Browser
  2. jQuery supports Ajax
  3. Rich Selectors
  4. DOM Manipulation

etc.

Using the Code

The Web Service methods that I will use revolve around client. Having set up a web site in Visual Studio 2008, I have added a new item of type "Web Service" to the project, calling it Common.asmx. The code-behind - Common.cs - is automatically generated within the App_Code folder.

The full code for that class file is as follows:

ClientDataContext db = new ClientDataContext();
public Common()
{
} 
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Client InsertClient(string BizName)
{
    Client objClient = new Client();
    objClient.BizName = BizName;
    InsertData(objClient);
    return objClient;
}

public void InsertData(Client objClient)
{
    db.Clients.InsertOnSubmit(objClient);
    db.SubmitChanges();
}	

I have used LINQ for database operation Insert client and return Id.

Create a dbml file named Client.

Include JQuery library:

Return result as Json format following attribute will be responsible:

 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  

and important, do not forget to add attribute for webservice class:

[System.Web.Script.Services.ScriptService]

HTML code is:

<input type="text" id="txtBizName" />
<input type="button" id="Save" value="Save" />

Now JavaScript for achieving Ajax with Jquery library:

  <script language="javascript" type="text/javascript">
        $(document).ready(function() {
            $('#Save').click(InsertClient);
        }
    );
        function InsertClient() {
            var BizName = $('#txtBizName').val();
            alert(BizName);
            $.ajax({
                url: "Common.asmx/InsertClient",
                type: "POST",
                dataType: "json",
                data: "{BizName:'" + BizName + "'}",
                contentType: "application/json; charset=utf-8",
                success: function(msg) {
                    $('#status').html('Id: '+msg['d']['Id']);
                },
                error: function(e) {
                    $('#status').innerHTML = "Unavailable";
                }
            });
        }
    </script> 

Description

Add a reference of JQuery library:

<script src="jquery-1.3.2.min.js" type="text/javascript"></script> 

Then a click event is registered with the button which will invoke the InsertClient () function:

  $(document).ready(function() {
            $('#Save').click(InsertClient);
        }
    ); 

Document.Ready() makes sure code is executed only when a page is fully loaded. We often place code blocks inside this Document.Ready() event.

After that is the InsertClient() function that is fired when the button is clicked. It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties. Type specifies the HTTP method, which in this case is POST. URL specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property. In this case, BizName parameters are being passed, as we are calling the method that retrieves the entire collection of Client. The contentType and dataType MUST be specified. Following this are two further functions: success defines what should be done if the call is successful and get Id of client with msg['d']['Id'], and error handles exceptions that are returned.

You can see that an object with a property - d - is returned and we display Id of client.

 $('#status').html('Id: '+msg['d']['Id']);  

Summary

With the marching forward of AJAX to the forefront of building rich interactive websites, jQuery as the lightweight yet powerful JavaScript library also gains ever more prominence. Reflecting on the trend of harnessing the best of the web, this article paints in broad strokes some of the characteristics of jQuery and how we can integrate jQuery into ASP.NET.

History

  • 18th March, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rajendra Malav
Software Developer (Senior) Radicle software pvt ltd.
India India
Member
Asp.Net Programmer

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionwhat is 'd' here....memberprofessional.anil29 Jul '12 - 6:06 
How did you got the property - d - with this? I can't see any relationship of 'd' property.
 
from where it associated 'd' property in the msg object?
GeneralMy vote of 3memberajeethuk16 Jul '12 - 1:10 
okay
QuestionGreat Articlemembermethcoo20 May '12 - 23:33 
This article is very use full me since i am a new to EDML.
GeneralMy vote of 4membereasetolearndotnet20 Jan '11 - 18:19 
Nice Article for implementing jquery for calling web services
GeneralMy vote of 1memberSelvin8 Apr '10 - 0:27 
1. what "advanced" is showed in this article ?
2. more interesting things you can find here http://encosia.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 18 Mar 2010
Article Copyright 2010 by Rajendra Malav
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid