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

Home > Blogs > Developer Visual Studio / ASP.NET > Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using WCF – Part 2 by Dan Wahlin

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

Like This Blog 3 Dan Wahlin
Added by April 11, 2012

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

Videos You May Like

A Simple Introduction to Cisco CML2

0 3877 0

Mark Jacob, Cisco Instructor, presents an introduction to Cisco Modeling Labs 2.0 or CML2.0, an upgrade to Cisco’s VIRL Personal Edition. Mark demonstrates Terminal Emulator access to console, as well as console access from within the CML2.0 product. Hello, I’m Mark Jacob, a Cisco Instructor and Network Instructor at Interface Technical Training. I’ve been using … Continue reading A Simple Introduction to Cisco CML2

Creating Dynamic DNS in Network Environments

0 641 1

This content is from our CompTIA Network + Video Certification Training Course. Start training today! In this video, CompTIA Network + instructor Rick Trader teaches how to create Dynamic DNS zones in Network Environments. Video Transcription: Now that we’ve installed DNS, we’ve created our DNS zones, the next step is now, how do we produce those … Continue reading Creating Dynamic DNS in Network Environments

Cable Testers and How to Use them in Network Environments

0 724 1

This content is from our CompTIA Network + Video Certification Training Course. Start training today! In this video, CompTIA Network + instructor Rick Trader demonstrates how to use cable testers in network environments. Let’s look at some tools that we can use to test our different cables in our environment. Cable Testers Properly Wired Connectivity … Continue reading Cable Testers and How to Use them in Network Environments

Write a Comment

See what people are saying...

  1. Pingback: Using a Custom HttpHandler to get data ASP.NET using Ajax and jQuery

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

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

Share your thoughts...

Please fill out the comment form below to post a reply.