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

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

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

Like This Blog 4 Dan Wahlin
Added by June 6, 2012

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

Videos You May Like

A Simple Introduction to Cisco CML2

0 3876 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

Cable Testers and How to Use them in Network Environments

0 720 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

Government Edition – Encrypting a USB Flash Drive in Windows 10

0 274 2

In this video, Security Instructor Mike Danseglio demonstrates how to use BitLocker in Window 10 to secure files on a USB Flash drive that adhere to stricter data protection requirements as found inside Government entities. BitLocker 2-day instructor-led training is now available at Interface: BITLOCK: Planning and Deploying BitLocker Drive Encryption Training Video Transcription: Hi. … Continue reading Government Edition – Encrypting a USB Flash Drive in Windows 10

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 Applications using Ajax and jQuery – Part I by Dan Wahlin | | Interface Technical Training BlogInterface Technical Training Blog

  3. 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

Share your thoughts...

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