Book Image

ASP.NET MVC 2 Cookbook

Book Image

ASP.NET MVC 2 Cookbook

Overview of this book

ASP.NET MVC, one of the latest web development platforms from Microsoft, brings the power of MVC programming to ASP.NET development. It simplifies the task of application development and maintenance for developers. However, ASP.NET MVC is filled with so many features that developers end up looking for solutions to the many problems that are encountered in their routine development tasks.ASP.NET MVC 2 Cookbook will provide solutions for the very specific problems that are encountered while developing applications with the ASP.NET MVC platform. It consists of many recipes containing step-by-step instructions that guide developers to effectively use the wide array of tools and features of ASP.NET MVC platform for web development ASP.NET MVC Cookbook is a collection of recipes that will help you to perform your routine development tasks with ease using the ASP.NET MVC platform. In this book you will be walked through the solution to several specific web application development problems. Each recipe will walk you through the creation of a web application, setting up any Visual Studio project requirements, adding in any external tools, and finally the programming steps needed to solve the problem. The focus of the book is to describe the solution from start to finish. The book starts off with recipes that demonstrate how to work effectively with views and controllers – two of the most important ingredients of the ASP.NET MVC framework. It then gradually moves on to cover many advanced routing techniques. Considering the importance of having a consistent structure to the site, the book contains recipes to show how to build a consistent UI and control its look with master pages. It also contains a chapter that is packed with many recipes that demonstrate how to gain control of data within a view. As the book progresses through some exciting recipes on performing complex tasks with forms, you will discover how easy it is to work with forms to jazz up the look of your web site. Building large applications with ease is one of the prime features of the MVC model. Therefore, this book also focuses on tools and features that make building large applications easier to manage. As data plays an important role in the MVC architecture, there are ample recipes dedicated to cover data validation, access, and storage techniques. Finally, the book demonstrates how to enhance the user experience of your visitors by controlling the data at the application, session, caching, and cookie level. By the end of this book, you will have explored a wide array of tools and features available with the ASP.NET MVC platform
Table of Contents (16 chapters)
ASP.NET MVC 2 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface

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. 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. 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. 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. 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. 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. 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. 7. Hit F5 and see the result!

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

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