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
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
You May Also Like
AJAXX, ASP.NET, JavaScrip, JSON, MVC, WCF, Web Services, Web.config, WebGet, WebInvoke, X jQuery
Cable Testers and How to Use them in Network Environments
0 654 1This 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
Configuring Windows Mobility Center and How to Turn it On and Off
1 1404 1Video transcription Steve Fullmer: In our Windows training courses, we often share information about the Windows 8.1 Mobility Center. Mobility Center was introduced for mobile and laptop devices in Windows 7. It’s present and somewhat enhanced in Windows 8. Since we don’t have mobile devices in our classrooms, I decided to take a little bit … Continue reading Configuring Windows Mobility Center and How to Turn it On and Off
How to use AWS CloudFormation templates to automate solutions inside Amazon AWS
0 380 0In the AWS Class here at Interface, we actually build fully automated solutions with AWS CloudFormations. Here’s an overview of using AWS templates using CloudFormation. CloudFormation is basically an “infrastructure-as-code tool” where you can go into a declarative document and define all the resources that you want and feed the document into the CloudFormation … Continue reading How to use AWS CloudFormation templates to automate solutions inside Amazon AWS
Pingback: Using a Custom HttpHandler to get data ASP.NET using Ajax and jQuery
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
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