Consuming a JSON with jQuery

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

Getting ready

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.

Note

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.

How to do it...

  1. First, make sure you have a good copy of the JSON.NET libraries in the dependencies folder. Then add a reference to it from your project.
  2. Then open up your 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();
    }
    
  3. Now you need to add a new view in the 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.
  4. Open up the new view and then add a call into the ViewData for the ProductView JSON that you just created.

    Views/Home/ProductJson.aspx:

    <%= ViewData["ProductView"] %>
    
  5. Next you need to make sure that you have a reference to jQuery in your master page. Open the Views/Site.Master file. Then locate the jquery script file in the Scripts directory, and drag it into the head of your master page.
  6. Now, focus on the rendering side of this problem. Open up the 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>
    
  7. Hit F5 and see the result!
    How to do it...

And if you navigate to /Home/ProductJson you should see the following.

How to do it...

How it works...

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.

There's more...

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.

See Also

  • Link to the Taking Action in Your Controllers chapter for creating a JSON result
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset