Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using ASP.NET MVC part 3 by Dan Wahlin

In my previous post I discussed how Windows Communication Foundation (WCF) could be used to serve up JSON data to applications. WCF is one of several different technologies that can be used to convert server-side objects into JSON data that can be consumed by Ajax clients. Examples of additional technologies that can be used are shown next:

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

With WCF you can use the WebGet or WebInvoke attributes to convert regular SOAP methods into JSON methods. An example of applying the WebGet attribute (shown in the previous post) is shown next:

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
           };
  }
}

In this post I'll discuss how ASP.NET MVC can be used to serve up JSON data to Ajax clients.

Using ASP.NET MVC to Server JSON Data

ASP.NET MVC provides one of the easiest and most straightforward ways to serve up JSON data to Ajax clients. To use it you don't have to worry about configuring a lot of data in web.config or adding special attributes on top of classes or methods as with ASP.NET Web Services or WCF.

To get started using ASP.NET MVC to serve up JSON, create a new ASP.NET MVC project in Visual Studio and add a new Controller class into the Controllers folder. I normally name my initial JSON-specific controller DataServiceController.cs. Once the controller is created you can add a new action into it. An example of adding a GetQuote() action is shown next:

public ActionResult GetQuote(string symbol)
{
    //Convert objects into JSON that can be sent to Ajax clients
}

 

To convert an object or collection of objects into JSON you can use the built-in Json() method exposed by the base Controller class that your controller inherits from. An example of using it to return a security object retrieved through a repository class (a class responsible for making database calls) is shown next:

public ActionResult GetQuote(string symbol)

{
     return Json(_SecurityRepository.GetSecurity(symbol));
}

This code calls into the GetSecurity() method of a repository class to retrieve a custom security object. The object is then converted into JSON using the Json() method available in ASP.NET MVC and returned from the GetQuote() controller action. Although this code works fine, if the Ajax client tries to call GetQuote() using a GET request the call will fail. That's because the Json() method supports POST requests by default. To enable GET requests a JsonRequestBehavior enum value can be passed to the second parameter of the Json() method as shown next:

public ActionResult GetQuote(string symbol)
{
        return Json(_SecurityRepository.GetSecurity(symbol), JsonRequestBehavior.AllowGet);
}

To call the GetQuote() method the following code can be used by the Ajax client:

function getQuote(sym) {
            $.getJSON('/DataService/GetQuote', { symbol: sym }, function(data) {
                    //process data returned form the controller action
            });
}

This code uses the jQuery getJSON() function to call the GetQuote() action and passes the stock symbol as an object literal. If the call succeeds the callback function will be invoked and security object data can be accessed through the data parameter.
Conclusion

In this post you've seen how ASP.NET MVC can be used to serve JSON data to an Ajax-enabled client. In the next post I'll discuss how custom ASP.NET HttpHandlers can be used to serve JSON.

Part 1: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Part I by Dan Wahlin

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

Part 3: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using ASP.NET MVC part 3 by Dan Wahlin
Enjoy!
Dan Wahlin
.NET Developer Instructor
Interface Technical Training

Posted in Developer Visual Studio / ASP.NET, Web Development | Posted in , , , , , , , , , , | 3 Comments

Your Feedback: (3 Responses)

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

  • Robert Bonham says:

    Thanks for taking the time to do these great post. Keep them coming.

  • Pingback: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using WCF – Part 2 by Dan Wahlin | | Interface Technical Training BlogInterface 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="">