Tải bản đầy đủ - 0 (trang)
Chapter 6. Enhancing Your Site with AJAX

Chapter 6. Enhancing Your Site with AJAX

Tải bản đầy đủ - 0trang

For example, let’s say that you have the following document, ajax_content.html, that

you’d like to asynchronously insert into a page:

This is the AJAX content!





And here’s the page into which you want to insert this content:





Partial Rendering Demo











This example uses the
element to mark where you want to

insert the dynamic content. You can then populate the
element

with the server-side content in ajax_content.html using the jQuery .load() method:

$("#container").load('ajax_content.html')



The .load() method makes an asynchronous request for the server-side content, then

injects it into the #container element. After the call, the DOM will include the dynamically retrieved server-side content:





Partial Rendering Demo





This is the AJAX content!











As this example shows, the partial rendering approach is a simple and effective way to

dynamically update sections of your web pages. What’s more, it’s incredibly easy to

implement in an ASP.NET MVC application!



Rendering Partial Views

For the most part, ASP.NET MVC treats a partial rendering request the same as any

other request—the request is routed to the appropriate controller action, and the controller action performs any logic that it needs to.

The difference occurs toward the end of the request, when it comes time to render the

view. Whereas the normal course of action might be to use the Controller.View()

helper method to return a ViewResult, you instead call the Controller.Partial() helper

to return a PartialViewResult. This is very similar to the ViewResult, except that it only

renders the content of the view—it does not render the view’s layout.

To demonstrate the difference, let’s compare the rendered markup from a partial view

of an Auction with the rendered markup generated for the “normal” view of an Auction.



112 | Chapter 6: Enhancing Your Site with AJAX



www.it-ebooks.info



Rendering a “normal” view

The following controller action (AuctionsController.cs) calls the Controller.View()

helper method that you’re already familiar with:

public class AuctionsController : Controller

{

public ActionResult Auction(long id)

{

var db = new DataContext();

var auction = db.Auctions.Find(id);

return View("Auction", auction);

}

}



Its corresponding Auction view (Auction.cshtml) looks like this:

@model Auction

@Model.Title




@Model.Title



Current Price:

@Model.CurrentPrice





Description





@Model.Description





This combination produces the final rendered HTML shown in Example 6-1.

Example 6-1. Rendered markup for “normal” Auction view



























EBuy: The ASP.NET MVC Demo Site









  • Home/Outdoors


  • Collectibles






  • Xbox 360 Kinect Sensor with Game Bundle




    Xbox 360 Kinect Sensor with Game ↵<br /><br />Bundle



    Closing in 4 days, 19 hours







    Current Price:

    $43.00





    Description





    You are the controller with Kinect for Xbox 360!







    © 2012 - EBuy: The ASP.NET MVC Demo Site











    Rendering a partial view

    Notice how the Auctions.cshtml view is rendered inside the site’s layout. This is exactly

    what users need to see when they browse to the page for the first time. But what if we

    want to reuse the layout markup that effectively stays the same for every page in the

    site, and update just the auction information in order to display the details of another

    auction without the user being required to navigate to another page?

    The answer is to use the Controller.PartialView() method to create a PartialViewRe

    sult instead of the ViewResult that the Controller.View() method generates:

    public class AuctionsController : Controller

    {

    public ActionResult Auction(long id)

    {

    var db = new DataContext();



    114 | Chapter 6: Enhancing Your Site with AJAX



    www.it-ebooks.info



    var auction = db.Auctions.Find(id);

    return View("Auction", auction);

    }

    public ActionResult PartialAuction(long id)

    {

    var db = new DataContext();

    var auction = db.Auctions.Find(id);

    return PartialView("Auction", auction);

    }

    }



    Notice how nothing else has changed except the switch from the View() method to the

    PartialView() method. The PartialViewResult can even use exactly the same views

    that the ViewResult depends on. In fact, the PartialViewResult and ViewResult are

    nearly identical, except for one very important difference: the PartialViewResult renders only the markup in the view itself and does not render any layout or master page

    that the view may specify. What’s more, partial views behave the same way as normal

    views, so you are free to use any type of syntax you like (such as the Razor syntax) and

    make full use of ASP.NET MVC view functionality such as HTML helpers.

    Since partial pages do not execute the layout, you may have to include

    some dependencies, such as CSS or JavaScript, directly in the partial

    view rather than including them in the page’s layout.



    This means that—using the same view shown in Auction.cshtml in the previous section

    —the PartialView result will render the markup in Example 6-2.

    Example 6-2. Rendered markup for the partial auction view

    Xbox 360 Kinect Sensor with Game Bundle




    Xbox 360 Kinect Sensor with Game ↵<br /><br />Bundle



    Closing in 4 days, 19 hours







    Current Price:

    $43.00





    Description







    Partial Rendering | 115



    www.it-ebooks.info



    You are the controller with Kinect for Xbox 360!





    With these changes, you can now use the following jQuery client-side code to load the

    HTML for new auctions without having to navigate to a new page:

    function showAuction(auctionId) {

    $('#main').load('/Auctions/PartialAuction/' + auctionId);

    }



    If you write the previous snippet inside of a Razor view, you can leverage

    the ASP.NET MVC UrlHelper to generate the correct route to the Auc

    tionsController.Auction action.

    Simply replace this:

    '/Auctions/PartialAuction/' + auctionId



    with:

    '@Url("PartialAuction", "Auctions")/' + auctionId



    Managing complexity with partial views

    The previous example showed how you can use partial views to display a page without

    its layout. Partial views needn’t always be full pages, however—splitting a page into

    multiple partial views is often a very good way to help simplify an otherwise overwhelming and complex view.

    Perhaps the best example of managing complexity with partial views is when you need

    to display something in a foreach loop, as in the list of auctions shown in the following

    snippet:

    @model IEnumerable

    Auctions





    @foreach(var auction in Model) {



    @auction.Title




    @auction.Title



    Current Price:

    @auction.CurrentPrice





    Description





    @auction.Description





    116 | Chapter 6: Enhancing Your Site with AJAX



    www.it-ebooks.info



    }









    Take a close look at the markup inside of the foreach loop—does it remind you of

    something you’ve seen before? It’s exactly the same markup from Auctions.cshtml that

    we used as a partial rendering result!

    That means we should be able to replace that whole section with a call to the Html.Par

    tial() helper to render the partial view we’ve already created:

    @model IEnumerable

    Auctions





    @foreach(var auction in Model) {



    @Html.Partial("Auction", auction)



    }





    Notice how we can specify the model that the partial view renders by passing it as the

    second parameter to the Html.Partial() helper. This allows us to iterate through the

    entire list of Auction objects and apply the same view to each instance.

    As the examples in this section show, effectively applying partial views can not only

    help simplify each individual view and reduce the amount of duplicate code in your

    application, it is also a great way to maintain consistency throughout your site.



    JavaScript Rendering

    Although the prerendered HTML approach is very easy and effective, it can also be

    quite wasteful to transmit both the data you’d like to display and the markup to display

    it, when the browser is perfectly capable of creating that markup itself. Thus, the alternative to retrieving prerendered HTML from the server is to retrieve the raw data

    that you’d like to display, then use that data to create and update HTML elements by

    manipulating the DOM directly.

    In order to implement a client-side rendering approach, you must have two things: a

    server that can produce the serialized data, and client-side logic that knows how to

    parse the serialized data and convert it into HTML markup.



    JavaScript Rendering | 117



    www.it-ebooks.info



    Rendering JSON Data

    Let’s tackle the server-side piece first: responding to an AJAX request with serialized

    data. Before we can do this, however, we must decide what technique we are going to

    use to serialize that data.

    JavaScript Object Notation (JSON) is a simple and very effective format for transmitting

    data over the Web. JSON objects leverage two types of data structures to represent

    data: collections of name/value pairs, and ordered lists of values (aka arrays). And, as

    its name implies, JavaScript Object Notation is based on a subset of the JavaScript

    language, so all modern browsers already understand it.

    ASP.NET MVC offers native JSON support in the form of the JsonResult action result,

    which accepts a model object that it serializes into the JSON format. In order to add

    AJAX support to your controller actions via JSON, simply use the Controller.Json()

    method to create a new JsonResult containing the object to be serialized.

    To show the Json() helper and JsonResult in action, let’s add a JsonAuction action to

    the AuctionsController:

    public ActionResult JsonAuction(long id)

    {

    var db = new DataContext();

    var auction = db.Auctions.Find(id);

    return Json(auction, JsonRequestBehavior.AllowGet);

    }



    This new controller action responds to requests with the JSON-serialized version of

    the auction data. For example:

    {

    "Title": "XBOX 360",

    "Description": "Brand new XBOX 360 console",

    "StartTime": "01/12/2012 12:00 AM",

    "EndTime": "01/31/2012 12:00 AM",

    "CurrentPrice": "$199.99",

    "Bids": [

    {

    "Amount" : "$200.00",

    "Timestamp": "01/12/2012 6:00 AM"

    },

    {

    "Amount" : "$205.00",

    "Timestamp": "01/14/2012 8:00 AM"

    },

    {

    "Amount" : "$210.00",

    "Timestamp": "01/15/2012 12:32 PM"

    }

    ]

    }



    118 | Chapter 6: Enhancing Your Site with AJAX



    www.it-ebooks.info



    This snippet is a great example of JSON’s simplicity and elegance—notice how

    [ and ] define arrays and how property values can be simple data types or complex data

    types represented by JSON objects themselves. This syntax also has the positive side

    effect of making JSON data very human-readable.



    Avoiding JSON hijacking with JsonRequestBehavior

    Notice that the Json() method’s second parameter is JsonRequestBehavior.AllowGet,

    which explicitly informs the ASP.NET MVC Framework that it’s acceptable to return

    JSON data in response to an HTTP GET request.

    The JsonRequestBehavior.AllowGet parameter is necessary in this case because, by default, ASP.NET MVC disallows returning JSON in response to an HTTP GET request

    in order to avoid a potentially dangerous security vulnerability known as JSON hijacking. This vulnerability takes advantage of a glitch in the way that many browsers handle

    JavaScript







    While it looks like there is quite a bit going on in this example, it is actually quite simple:

    1. When the page loads, the script block at the bottom retrieves the client template

    markup from the inner HTML of the auction-template element.

    2. The script then passes the client template markup to the Mustache.compile()

    method to compile it into a JavaScript function, which it saves to the template

    variable.



    122 | Chapter 6: Enhancing Your Site with AJAX



    www.it-ebooks.info



    Tài liệu bạn tìm kiếm đã sẵn sàng tải về

    Chapter 6. Enhancing Your Site with AJAX

    Tải bản đầy đủ ngay(0 tr)

    ×