29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Listing 9-5. Adding the Summary Method to the CartController.cs File<br />

using System.Linq;<br />

using System.Web.Mvc;<br />

using SportsStore.Domain.Abstract;<br />

using SportsStore.Domain.Entities;<br />

using SportsStore.WebUI.Models;<br />

namespace SportsStore.WebUI.Controllers {<br />

public class CartController : Controller {<br />

private IProductRepository repository;<br />

public CartController(IProductRepository repo) {<br />

repository = repo;<br />

}<br />

// . . . other action methods omitted for brevity . . .<br />

}<br />

}<br />

public PartialViewResult Summary(Cart cart) {<br />

return PartialView(cart);<br />

}<br />

This simple method needs to render a view, supplying the current Cart (which will be obtained using the custom model<br />

binder) as view data. To create the view, right-click the Summary action method and select Add View from the pop-up<br />

menu. Set the name of the view to Summary and click the OK button to create the Views/Cart/Summary.cshtml<br />

file. Edit the view so that it matches Listing 9-6.<br />

Listing 9-6. The Contents of the Summary.cshtml File<br />

@model SportsStore.Domain.Entities.Cart<br />

<br />

@Html.ActionLink("Checkout", "Index", "Cart",<br />

new { returnUrl = Request.Url.PathAndQuery },<br />

new { @class = "btn btn-default navbar-btn" })<br />

<br />

<br />

Your cart:<br />

@Model.Lines.Sum(x => x.Quantity) item(s),<br />

@Model.ComputeTotalValue().ToString("c")<br />

<br />

The view displays the number of items in the cart, the total cost of those items, and a link that shows the details of the cart to<br />

the user (and, as you will have expected by now, I have assigned the elements that the view contains to classes defined by<br />

Bootstrap). Now that I have created the view that is returned by the Summary action method, I can call the Summary action<br />

method in the _Layout.cshtml file to display the cart summary, as shown in Listing 9-7.<br />

Listing 9-7. Adding the Summary Partial View to the _Layout.cshtml File<br />

<br />

<br />

<br />

235

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!