Part 10: Final Updates to Navigation and Site Design, Conclusion
by Jon Galloway
The MVC Music Store is a tutorial application that introduces and explains step-by-step how to use ASP.NET MVC and Visual Studio for web development.
The MVC Music Store is a lightweight sample store implementation which sells music albums online, and implements basic site administration, user sign-in, and shopping cart functionality.
This tutorial series details all of the steps taken to build the ASP.NET MVC Music Store sample application. Part 10 covers Final Updates to Navigation and Site Design, Conclusion.
We’ve completed all the major functionality for our site, but we still have some features to add to the site navigation, the home page, and the Store Browse page.
Creating the Shopping Cart Summary Partial View
We want to expose the number of items in the user’s shopping cart across the entire site.
We can easily implement this by creating a partial view which is added to our Site.master.
As shown previously, the ShoppingCart controller includes a CartSummary action method which returns a partial view:
[!code-csharpMain]
1: //
2: // GET: /ShoppingCart/CartSummary
3: [ChildActionOnly]
4: public ActionResult CartSummary()
5: {
6: var cart = ShoppingCart.GetCart(this.HttpContext);
7:
8: ViewData["CartCount"] = cart.GetCount();
9: return PartialView("CartSummary");
10: }
To create the CartSummary partial view, right-click on the Views/ShoppingCart folder and select Add View. Name the view CartSummary and check the “Create a partial view” checkbox as shown below.
The CartSummary partial view is really simple - it’s just a link to the ShoppingCart Index view which shows the number of items in the cart. The complete code for CartSummary.cshtml is as follows:
[!code-cshtmlMain]
1: @Html.ActionLink("Cart
2: (" + ViewData["CartCount"] + ")",
3: "Index",
4: "ShoppingCart",
5: new { id = "cart-status" })
We can include a partial view in any page in the site, including the Site master, by using the Html.RenderAction method. RenderAction requires us to specify the Action Name (“CartSummary”) and the Controller Name (“ShoppingCart”) as below.
[!code-cshtmlMain]
1: @Html.RenderAction("CartSummary",
2: "ShoppingCart")
Before adding this to the site Layout, we will also create the Genre Menu so we can make all of our Site.master updates at one time.
Creating the Genre Menu Partial View
We can make it a lot easier for our users to navigate through the store by adding a Genre Menu which lists all the Genres available in our store.
We will follow the same steps also create a GenreMenu partial view, and then we can add them both to the Site master. First, add the following GenreMenu controller action to the StoreController:
[!code-csharpMain]
1: //
2: // GET: /Store/GenreMenu
3: [ChildActionOnly]
4: public ActionResult GenreMenu()
5: {
6: var genres = storeDB.Genres.ToList();
7: return PartialView(genres);
8: }
This action returns a list of Genres which will be displayed by the partial view, which we will create next.
Note: We have added the [ChildActionOnly] attribute to this controller action, which indicates that we only want this action to be used from a Partial View. This attribute will prevent the controller action from being executed by browsing to /Store/GenreMenu. This isn’t required for partial views, but it is a good practice, since we want to make sure our controller actions are used as we intend. We are also returning PartialView rather than View, which lets the view engine know that it shouldn’t use the Layout for this view, as it is being included in other views.
Right-click on the GenreMenu controller action and create a partial view named GenreMenu which is strongly typed using the Genre view data class as shown below.
Update the view code for the GenreMenu partial view to display the items using an unordered list as follows.
[!code-cshtmlMain]
1: @model IEnumerable<MvcMusicStore.Models.Genre>
2: <ul id="categories">
3: @foreach (var genre in Model)
4: {
5: <li>@Html.ActionLink(genre.Name,
6: "Browse", "Store",
7: new { Genre = genre.Name }, null)
8: </li>
9: }
10: </ul>
Updating Site Layout to display our Partial Views
We can add our partial views to the Site Layout (/Views/Shared/_Layout.cshtml) by calling Html.RenderAction(). We’ll add them both in, as well as some additional markup to display them, as shown below:
[!code-cshtmlMain]
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>@ViewBag.Title</title>
5: <link href="@Url.Content("~/Content/Site.css")"
6: rel="stylesheet"
7: type="text/css" />
8: <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")"
9: type="text/javascript"></script>
10: </head>
11: <body>
12: <div id="header">
13: <h1><a href="/">ASP.NET MVC MUSIC
14: STORE</a></h1>
15: <ul id="navlist">
16: <li class="first">
17: <a href="@Url.Content("~")" id="current">
18: Home</a></li>
19: <li><a href="@Url.Content("~/Store/")">Store</a></li>
20: <li>@{Html.RenderAction("CartSummary", "ShoppingCart");}</li>
21: <li><a href="@Url.Content("~/StoreManager/")">
22: Admin</a></li>
23: </ul>
24: </div>
25: @{Html.RenderAction("GenreMenu", "Store");}
26: <div id="main">
27: @RenderBody()
28: </div>
29: <div id="footer">
30: built with <a href="http://asp.net/mvc">ASP.NET MVC 3</a>
31: </div>
32: </body>
33: </html>
Now when we run the application, we will see the Genre in the left navigation area and the Cart Summary at the top.
Update to the Store Browse page
The Store Browse page is functional, but doesn’t look very good. We can update the page to show the albums in a better layout by updating the view code (found in /Views/Store/Browse.cshtml) as follows:
[!code-cshtmlMain]
1: @model MvcMusicStore.Models.Genre
2:
3: @{
4: ViewBag.Title = "Browse Albums";
5: }
6:
7: <div class="genre">
8: <h3><em>@Model.Name</em> Albums</h3>
9:
10: <ul id="album-list">
11: @foreach (var album in Model.Albums)
12: {
13: <li>
14: <a href="@Url.Action("Details",
15: new { id = album.AlbumId })">
16: <img alt="@album.Title"
17: src="@album.AlbumArtUrl" />
18: <span>@album.Title</span>
19: </a>
20: </li>
21: }
22: </ul>
23: </div>
Here we are making use of Url.Action rather than Html.ActionLink so that we can apply special formatting to the link to include the album artwork.
Note: We are displaying a generic album cover for these albums. This information is stored in the database and is editable via the Store Manager. You are welcome to add your own artwork.
Now when we browse to a Genre, we will see the albums shown in a grid with the album artwork.
Updating the Home Page to show Top Selling Albums
We want to feature our top selling albums on the home page to increase sales. We’ll make some updates to our HomeController to handle that, and add in some additional graphics as well.
First, we’ll add a navigation property to our Album class so that EntityFramework knows that they’re associated. The last few lines of our Album class should now look like this:
[!code-csharpMain]
1: public virtual Genre Genre { get; set; }
2: public virtual Artist Artist { get; set; }
3: public virtual List<OrderDetail>OrderDetails { get; set; }
4: }
5: }
Note: This will require adding a using statement to bring in the System.Collections.Generic namespace.
First, we’ll add a storeDB field and the MvcMusicStore.Models using statements, as in our other controllers. Next, we’ll add the following method to the HomeController which queries our database to find top selling albums according to OrderDetails.
[!code-csharpMain]
1: private List<Album> GetTopSellingAlbums(int count)
2: {
3: // Group the order details by album and return
4: // the albums with the highest count
5: return storeDB.Albums
6: .OrderByDescending(a => a.OrderDetails.Count())
7: .Take(count)
8: .ToList();
9: }
This is a private method, since we don’t want to make it available as a controller action. We are including it in the HomeController for simplicity, but you are encouraged to move your business logic into separate service classes as appropriate.
With that in place, we can update the Index controller action to query the top 5 selling albums and return them to the view.
[!code-csharpMain]
1: public ActionResult Index()
2: {
3: // Get most popular albums
4: var albums = GetTopSellingAlbums(5);
5:
6: return View(albums);
7: }
The complete code for the updated HomeController is as shown below.
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Linq;
3: using System.Web.Mvc;
4: using MvcMusicStore.Models;
5:
6: namespace MvcMusicStore.Controllers
7: {
8: public class HomeController : Controller
9: {
10: //
11: // GET: /Home/
12: MusicStoreEntities storeDB = new MusicStoreEntities();
13: public ActionResult Index()
14: {
15: // Get most popular albums
16: var albums = GetTopSellingAlbums(5);
17:
18: return View(albums);
19: }
20: private List<Album> GetTopSellingAlbums(int count)
21: {
22: // Group the order details by album and return
23: // the albums with the highest count
24: return storeDB.Albums
25: .OrderByDescending(a => a.OrderDetails.Count())
26: .Take(count)
27: .ToList();
28: }
29: }
30: }
Finally, we’ll need to update our Home Index view so that it can display a list of albums by updating the Model type and adding the album list to the bottom. We will take this opportunity to also add a heading and a promotion section to the page.
[!code-cshtmlMain]
1: @model List<MvcMusicStore.Models.Album>
2: @{
3: ViewBag.Title = "ASP.NET MVC Music Store";
4: }
5: <div id="promotion">
6: </div>
7: <h3><em>Fresh</em> off the grill</h3>
8: <ul id="album-list">
9: @foreach (var album in Model)
10: {
11: <li><a href="@Url.Action("Details", "Store",
12: new { id = album.AlbumId })">
13: <img alt="@album.Title" src="@album.AlbumArtUrl" />
14: <span>@album.Title</span>
15: </a>
16: </li>
17: }
18: </ul>
Now when we run the application, we’ll see our updated home page with top selling albums and our promotional message.
Conclusion
We’ve seen that that ASP.NET MVC makes it easy to create a sophisticated website with database access, membership, AJAX, etc. pretty quickly. Hopefully this tutorial has given you the tools you need to get started building your own ASP.NET MVC applications!
|