Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

Calling an ASP.Net web service using jQuery and JSON.

Karl Schwirz

Let’s say you have a webpage where you need to call a service but cannot perform a post back.  Recently I was on a client engagement where we needed to improve page performance by dynamically loading a navigation tree with a potential for several thousand links.  We implemented a solution that would load each branch as the user clicked on the expanding icon by calling a web service via ajax and passing the required links back to the page and render them client side.  This saved immensely on the load time for the page and improved the user experience

This kind of solution can be applied to several situations such as complex data processing, dynamic loading, or combining them all into a seamless form submission process that would clear the form on post backs.

We can accomplish this process simply by grabbing an event, such as a button click, and collecting all the required information using jQuery.  Next using a JSON call, we can pass all the parameters to the web service and execute our code from there.

Here, I’ll start with a simple .aspx page with jquery, a textbox, and link that will be used to call the web service.

   1: <%@ Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ThisPage.cs" Inherits="ThisSolution.ThisProject.ThisFolder" %>


   3: <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

   4:     <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"/>

   5: </asp:Content>


   7: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

   8:     <asp:TextBox ID=”textBoxTextMode="MultiLine" runat="server"></asp:TextBox>

9: <a href=”#” class=”buttonClass”> Save </a>

10: <asp:Label ID=”successLabelrunat=”server”></asp:Label>

  11: </asp:Content>

Next, you will need to establish your web service and create an .asmx file.  There are a couple of important things to note here. Line 5 will be by default commented out.  So in order for us to make our JSON call we’re going to need this uncommented.  Also, notice I’m returning a string.  For the purposes of this demo I am going to return a string to the UI and display a message, but you can return any kind of object that can be serialized down to a primitive data type.

   1: [WebService(Namespace = "http://tempuri.org/")]

   2: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

   3: [System.ComponentModel.ToolboxItem(false)]

   4: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 

   5: [System.Web.Script.Services.ScriptService]

   6: public class wService : System.Web.Services.WebService

   7: {

   8:     [WebMethod()]

   9:     [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]

  10:     public string UpdateComment(string textBoxText)

  11:     {

  12:         var success = Service.CallToDb(textBoxText);


  14:         if(success)

  15:         {

  16:             return "Call to Database using text was successful";

  17:         }

  18:         else

  19:         {

  20:             return "Call to Database using text was not successful";

  21:         }

  22:     }

  23: }

I use a jQuery selector to pick up on the mouse click of the link and gather our data into an javascript object.  Note that when passing parameters through this object you have to name them the same way as you do in the parameter declaration of the web service.

When setting up the call to the service you’re going to want to remember to call the “JSON.stringify” function on your data object so that it serializes properly and that your contentType as well as dataType are configured properly as well.

   1: <script type='text/javascript>

   2:     $('.buttonClass').live('click', function(){

   3:         var text = $('#textBox').text();

   4:         var data = new Object();

   5:         data.textBoxText = text;


   7:         $.ajax({

   8:             type: "POST",

   9:             url: "/Ajax/WbServcie.asmx/UpdateComment",

  10:             data: JSON.stringify(data),

  11:             contentType: "application/json; charset=utf-8",

  12:             dataType: "json",

  13:             success: function(msg){

  14:                 $('#successLabel').val(msg);

  15:             },

  16:             error: function(msg){

  17:                 alert('Something, somewhere, has gone terribly wrong');

  18:                 return false;

  19:             }

  20:         });

  21: </script>

Once you get a response from the service, you can set any of your data that is returned.  In this case, we’re returning a string indicating the call to the database was successful and will set a label on the page to show that.

And that’s it.  With just a few simple configurations we have a quick call back to the server without having to run an expensive post back.

2 Comments. Leave new

Would there be any difference in MVC?

I haven’t implemented this particular solution in MVC yet, however my initial inkling would be yes you could use a solution very similar to this.
Depending on what you would be using the webservice for, in my case it was to avoid a full page post back to load a link tree, you could potentially use the same technique to call back to your controller instead. Which could save you the hassle of establishing a web service. That I have done before, and all it would require is some method attribute decoration in your controller. If you end up going down that road there’s plenty of documentation online blueprinting how to go about it.

Hope that helps

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>