- ASP.NET MVC 2 Cookbook
- Andrew Siemer, Richard Kimber
- 715字
- 2021-04-09 22:44:24
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.
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.
- 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.
- Then open up your
HomeController
. Add an action calledProductJson
. This method will generate some JSON for you, using your existingProduct
andCategory
data. Then enter the following code (notice that this is almost identical to the previous recipes except for the highlightedJsonConvert
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(); }
- Now you need to add a new view in the
Views/Home
folder that this action will pass its data down to. Name this viewProductJson.aspx
to correspond to the action that you just created. - Open up the new view and then add a call into the
ViewData
for theProductView
JSON that you just created.Views/Home/ProductJson.aspx:
<%= ViewData["ProductView"] %>
- 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 thejquery script
file in theScripts
directory, and drag it into the head of your master page. - Now, focus on the rendering side of this problem. Open up the
Product.aspx
view—in there you will need to add a newdiv
tag to output your JSON to. Then you will need to add some JavaScript to make a request for yourProductView
JSON and output it to thediv
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>
- Hit F5 and see the result!
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.
- 中文版CorelDRAW X7基礎培訓教程(移動學習版)
- 中文版After Effects 2021入門教程
- Animate 2022動畫制作:團體操隊形
- 中文版3ds Max 2024完全自學教程
- Premiere Pro 2022從新手到高手
- 3ds max & VRay產品造型設計經典
- Solid Works 2021產品設計標準教程
- SPSS進階分析與實務
- ASP.NET jQuery Cookbook
- AutoCAD 2019中文版計算機輔助繪圖全攻略
- Moldflow 2021模流分析從入門到精通(升級版)
- Linux Shell Scripting Cookbook
- Adobe創意大學InDesign產品專家認證標準教材(CS6修訂版)
- Photoshop+CorelDRAW平面設計案例實戰:從入門到精通(視頻自學全彩版)
- Instant Markdown