In this recipe, we will see how to consume JSON using jQuery. We will continue to use our Product
and Category
concepts to be displayed in our view. We will still depend on our ProductView
view model object to pass data to our view (we will just be using JavaScript to do it this time).
We will be starting from our ViewModel
recipe discussed earlier. But before we get to coding, we need to go grab a copy of jQuery (you may have a copy in the Scripts
folder already), which you can get from here: http://docs.jquery.com/Downloading_jQuery. Then we need to grab a copy of JSON.NET to help us quickly serialize our C# objects. You can get a copy of this here: json.codeplex.com/releases/view/37810.
This recipe uses JSON.NET as it is a quick and easy way to generate JSON from your C# classes in any context. If for some reason you are not able to use JSON.NET, or prefer to stay away from open source, you can just as easily use the JavaScriptSerializer
found in the .NET framework (http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx) in an MVC project, you can simply use the JsonResult
(covered in another recipe later) to serialize an instance of a class for you.
HomeController
. Add an action called ProductJson
. This method will generate some JSON for you, using your existing Product
and Category
data. Then enter the following code (notice that this is almost identical to the previous recipes except for the highlighted JsonConvert
call).Controllers/HomeController.cs:
public ActionResult ProductJson()
{
Product p = Builder<Product>
.CreateNew()
.Build();
Category c = Builder<Category>
.CreateNew()
.Build();
ProductView pv = new ProductView();
pv.CurrentCategory = c;
pv.CurrentProduct = p;
ViewData["ProductView"] = JsonConvert.SerializeObject(pv);
return View();
}
Views/Home
folder that this action will pass its data down to. Name this view ProductJson.aspx
to correspond to the action that you just created. ViewData
for the ProductView
JSON that you just created.Views/Home/ProductJson.aspx:
<%= ViewData["ProductView"] %>
Views/Site.Master
file. Then locate the jquery script
file in the Scripts
directory, and drag it into the head of your master page. Product.aspx
view—in there you will need to add a new div
tag to output your JSON to. Then you will need to add some JavaScript to make a request for your ProductView
JSON and output it to the div
tag.Views/Home/Product.aspx:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <div id="result"></div> <script> $(document).ready( $.getJSON('http://localhost:6324/home/productjson', function (data) { $('#result').html('<p>' + data.CurrentProduct.ProductName + '</p>'), } ) ); </script> </asp:Content>
And if you navigate to /Home/ProductJson
you should see the following.
For the most part, the logic is the same as our other recipes, in that we used NBuilder to generate some fake data for us. Instead of passing that generated data directly down to our view though, we used some jQuery functions to request the data after the client's Product view page loaded. We used the getJSON
method that takes the URL of the JSON and a callback method to perform operations on the result of the method call. In this case, our callback was defined directly in the initial function call.
We also used JSON.NET to help us with the serialization of our ProductView
class. We will cover more of this when we discuss actions and controllers and how to expose JSON directly from the action itself.
Obviously, this has quite a bit of power. The use of AJAX and jQuery in particular has reached out and touched just about every web application on the net in some way or the other. Using this method of data retrieval means that the pain of the post back and whole-page rendering doesn't need to be felt by the viewer nearly as often as before.