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

JavaScript for C# Developers – September 24, 2014

0 482 3

Is JavaScript worth taking the time to learn if I’m a server-side .NET developer? How much of C# carries over to JavaScript? In this recorded video from Dan Wahlin’s webinar on September 24,2014, Dan answers these questions and more while also discussing similarities between the languages, key differences, and the future of JavaScript (ES6). If … Continue reading JavaScript for C# Developers – September 24, 2014

How to clone a Windows Server 2012 or 2012 R2 Domain Controller

3 1451 3

One of the coolest new features in Window Server 2012 and Windows Server 2012 R2 is the ability to clone a Domain Controller. In the past, if we had virtualized Domain Controllers and we actually took a snapshot of it and then rolled back to that snapshot, it would break the logon service on that … Continue reading How to clone a Windows Server 2012 or 2012 R2 Domain Controller

Detailed Forensic Investigation of Malware Infections – April 21, 2015

4 592 5

How does an investigator hunt down and identify unknown malware? In this recording of our IT Security training webinar on April 21, 2015, Security expert Mike Danseglio (CISSP / CEH) performed several malware investigations on infected computers and identify symptoms, find root cause, and follow the leads to determine what’s happening. He demonstrated his preferred … Continue reading Detailed Forensic Investigation of Malware Infections – April 21, 2015

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.