Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using WCF – Part 2 by Dan Wahlin

In my previous post I discussed how to use ASP.NET Web Services to serve up JSON data to applications. As a quick review, there are several different techniques that can be used including the following:

1. ASP.NET Web Services (.asmx)
2. Windows Communication Foundation
3. ASP.NET MVC Controller/Action
4. Custom HttpHandler
5. Web API

With ASP.NET Web Services you can use the ScriptService attribute in .asmx files to convert regular SOAP methods into JSON methods. An example of applying the ScriptService attribute (shown in the previous post) is shown next:

[ScriptService]
[WebService(Namespace = http://interfacett.com/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService

{
    [WebMethod]
    public Customer GetCustomer(int custID)
    {
        //Simulate getting a "real" customer
        return new Customer
                    {
                        CustomerID = custID,
                        FirstName = "John",
                        LastName = "Doe"
                    };
    }
}

In this post I'll switch gears and introduce how Windows Communication Foundation can be used to serve up JSON data to Ajax clients.

Using Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is normally used to serve up SOAP/XML messages. However, with a little bit of code you can modify methods to return JSON data if desired. This is done by using the WebGet or WebInvoke attributes. The WebGet attribute is used for GET requests (as the name infers) whereas WebInvoke defaults to POST but can also be used with other verbs such as GET, DELETE, PUT, etc.
An example of defining two WCF operations that include the WebGet attribute is shown next. By including WebGet above each operation JSON data will automatically be returned or accepted as appropriate.

using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web; 

[ServiceContract]
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class CustomerService
{

[WebGet]

       [OperationContract]
       public List<Customer> GetCustomers()
       {
           return new List<Customer>{
            new Customer
               {
                ID = 3,
                FirstName = "John",
                LastName = "Doe"
               },
            new Customer
               {
                ID = 4,
                FirstName = "Jane",
                LastName = "Doe"
               }
        };
       }
 
       [WebGet]   

[OperationContract]

       public OperationStatus SaveCustomer(Customer cust)
       {
           //Simulate inserting a customer…assume it works
           return new OperationStatus
           {
               Status = true,
               Message="Customer Saved: " + cust.FirstName + " " + cust.LastName
           };
       }
}

A browser can communicate with the service to retrieve Customer objects and even send a Customer object to the server using several different jQuery methods including get(), post(), getJSON(), and ajax(). The following code shows how the getJSON() function can be used to call the GetCustomers() method defined in the WCF service shown earlier:

$('#GetCustomerButton').click(function () {
$.getJSON('../CustomerService.svc/GetCustomers',
function (data) {
var cust = data.d[0];
          $('#ID').text(cust.ID);
$('#FirstName').val(cust.FirstName);
&lt $('#LastName').val(cust.LastName);
});
});

Although post() or ajax() are normally used to send data to the server, get() or getJSON() can also be used just as easily in many cases depending on your application's needs. An example of using getJSON() to send a client-side customer object up to the SaveCustomer() WCF operation and then handle the JSON data that's returned is shown next. If making a GET request to send data to the server isn't your preferred approach (due to security or the size of the data) then use post() or ajax() instead.

$('#SaveCustomerButton').click(function () {
    var customer = {
        ID: $('#ID').text(),
        FirstName: $('#FirstName').val(),
        LastName: $('#LastName').val()
    };
 
    $.getJSON('../CustomerService.svc/SaveCustomer', 'cust=' +               JSON.stringify(customer), function (data) {
        alert(data.d.Message);
    });
});

Looking through the code you'll notice that once the customer object is created, it's converted to a string using the JSON.stringify() function and then sent using getJSON(). The stringify() function is built-into modern browsers but you can get a script that allows the same functionality to work in older browsers.

The data that is sent up to the server is prefixed with "cust" because the WCF service operation accepts a parameter named cust as shown next:

[WebGet]   
[OperationContract]
public OperationStatus SaveCustomer(Customer cust) {…}

The incoming data is automatically mapped to this parameter and the associated properties by WCF. There's much more to WCF's Ajax/JSON features than I've covered here. You can get additional details here.

 Conclusion

In this post you've seen how Windows Communication Foundation (WCF) can be used to serve JSON data to an Ajax-enabled client. In the next post I'll discuss how ASP.NET MVC can be used to serve JSON.

Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using WCF – Part 1

Enjoy!
Dan Wahlin
.NET Developer Instructor
Interface Technical Training

Posted in Developer Visual Studio / ASP.NET | Posted in , , , , , , , , , | 2 Comments

Your Feedback: (2 Responses)

  • Pingback: Getting Data in and out of ASP.NET with ASP.NET MVC – Dan WahlinInterface Technical Training Blog

  • Pingback: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Part I by Dan Wahlin | Interface Technical Training Blog

  • 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 class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">