P. 1
MVC Music Store - Tutorial - V2.0

MVC Music Store - Tutorial - V2.0

|Views: 141|Likes:
Published by ALi

More info:

Published by: ALi on May 17, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





Our Shopping Cart Controller will need to communicate some complex information to its views which

doesn’t map cleanly to our Model objects. We don’t want to modify our Models to suit our views; Model

classes should represent our domain, not the user interface. One solution would be to pass the information
to our Views using the ViewBag class, as we did with the Store Manager dropdown information, but passing
a lot of information via ViewBag gets hard to manage.

A solution to this is to use the ViewModel pattern. When using this pattern we create strongly-typed classes
that are optimized for our specific view scenarios, and which expose properties for the dynamic
values/content needed by our view templates. Our controller classes can then populate and pass these
view-optimized classes to our view template to use. This enables type-safety, compile-time checking, and
editor IntelliSense within view templates.

We’ll create two View Models for use in our Shopping Cart controller: the ShoppingCartViewModel will
hold the contents of the user’s shopping cart, and the ShoppingCartRemoveViewModel will be used to

display confirmation information when a user removes something from their cart.

Let’s create a new ViewModels folder in the root of our project to keep things organized. Right-click the
project, select Add / New Folder.

MVC Music Store Tutorial v2.0 – http://mvcmusicstore.codeplex.com – Tutorial under Creative Commons Attribution 3.0 License
Page 108

Name the folder ViewModels.

Next, add the ShoppingCartViewModel class in the ViewModels folder. It has two properties: a list of Cart
items, and a decimal value to hold the total price for all items in the cart.

using System.Collections.Generic;
using MvcMusicStore.Models;

namespace MvcMusicStore.ViewModels

public class ShoppingCartViewModel

MVC Music Store Tutorial v2.0 – http://mvcmusicstore.codeplex.com – Tutorial under Creative Commons Attribution 3.0 License
Page 109


public List CartItems { get; set; }
public decimal CartTotal { get; set; }



Now add the ShoppingCartRemoveViewModel to the ViewModels folder, with the following four properties.

namespace MvcMusicStore.ViewModels

public class ShoppingCartRemoveViewModel

public string Message { get; set; }
public decimal CartTotal { get; set; }
public int CartCount { get; set; }
public int ItemCount { get; set; }
public int DeleteId { get; set; }



You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->