Syllabus Schedule Project Labs Canvas Server Access CSS Tutorial Assignment 1 Assignment 2 Assignment 3 Assignment 4 Assignment 5 Assignment 6 Assignment 7 Assignment 8 Assignment 9

Assignment 8 - Shopping Cart & Customer Info

This week you will create a shopping cart and write customer information to the database. Shopping cart data can be stored using cookies, a database, or session. The database approach is the most robust approach and is used by Amazon and other large e-commerce sites. Advantages of this approach are that the data persists indefinitely and the user can retrieve their cart items from different devices (with a login). Storing shopping cart data in a database also allows user behavior to be analyzed (data mining) for insights on how to improve the site and its features.

Users typically are not required to sign-in to use a shopping cart since this could deter people from putting items in their cart. This creates a dilemma since the web site needs a method for tracking the state of individual users. Fortunately ASP.NET (and most server-side programming frameworks) automatically creates a unique identifier for each user, the SessionID. It is a string of 24 random letters and numbers that is stored in a cookie on the user's computer and is included with each request. The session ID may be retrieved with "Session.SessionID". When using a database shopping cart this ID is written to the database along with the cart data.

Tip: The default routing includes an optional parameter named "id". We have not defined any additional routes so "id" is the only parameter that will be recognized unless the name of the parameter is given in the query string. For example, the URL "/music/Detail/B0068CEGT0" is passing ASIN but the controller retrieves "id."
public ActionResult Detail(string id)

  1. music/detail - Clicking the shopping cart button calls a controller handler named "AddToCart." This handler adds the item to tblCart in the database and displays the Cart view. Steps: 
    1. Database: tblCart Your application will be using two databases: the remote read-only database with product information and a local read-write database for cart, customer, and order information.
    2. Create a new database named Music and add a table named tblCart with the fields shown in the image. This database contains the subset of product information needed for the order.
    3. web.config: Add connection strings for the new database.
    4. Model: A model is needed to represent the shopping cart data. Create a new model named MusicCartModel in MusicModels with properties matching the database fields. In C# varchar() fields are type string and float is decimal.
    5. ShoppingCart Class: The shopping cart class contains the functionality of a shopping cart: adding items, updating quantities, removing items, listing items, etc. Inside your DataRepository folder create a new class named "MusicCartRepository"  Replace the default code with the source code for the shopping cart. This will add shopping cart functionality to your application as shown in the image: Shopping Cart class
    6. You do not need to make any changes to MusicCartRepository.
    7. Add to cart: copy and paste the HTML for the Add to Cart button from the sample to your details view. Add a tilde (~) to the beginning of the path for both href & src. MVC will replace the tilde with the path to the root folder when the page is rendered. The ASIN of the current product is added with Razor syntax:

      <a href="~/music/addToCart/@Model.Asin"> ...

    8. Controller: The controller needs to access cart methods. Instantiate a MusicCartRepository object named musicCartRepository (similar to the existing MusicRepository object).
    9. The controller needs a handler for adding items to the cart. Add a new handler to the controller named AddToCart. Add code to retrieve ASIN (id in the controller) to two of the methods provided in musicCartEntity: the first to add Asin to the cart and the second to get all items in the cart to display to the user.
    10. SessionID: When the Session is not storing data .NET generates a new sessionID for each request. The shopping cart depends upon a static sessionID. The solution is to add some data to the session. Add the following line of code to your AddToCart handler:

      if(Session["stuff"] == null) Session["stuff"] = "Go Vikings!";

    11. Add another handler to the controller named "Cart" that displays the items in the cart.
    12. View: Add a view named Cart, template is List, model is musicCartModel.
    13. Test!
    14. Format the layout of cart with a thumbnail images, add/remove links, link to checkout, etc. See sample site for HTML and CSS. The price totals and shipping are calculated using Razor syntax. Before the foreach loop define a few variables:
      @{
          double itemTotal = 0;
          double subTotal = 0;
          int totalQty = 0;
          double discount = 0.8;
          double shippingBase = 3.99;
          double shippingItem = .99;
      }
      
      Inside the foreach loop calculate values for individual items:
         @{
         double price = item.Price / 100 * discount;
         itemTotal = @item.Qty * price;
         subTotal += itemTotal;
         totalQty += @item.Qty;
         }
      
      
    15. Add another handler to the controller named RemoveFromCart. It is similar to AddToCart.
  2. music/Signin: The checkout process writes customer and order information to the database. It uses three views: signin, checkout, and confirmation. The first view named SignIn gets the customer's email. The HttpPost handler for SignIn checks the database to see if the customer is new or returning and displays the checkout view with an appropriate message. Steps:
    1. tblCustomersModel: Create two new models in MusicModels. The first named SignInModel contains a single Property "Email." Make it required and validate it as a valid email format. See SnowBoardModel for validation syntax.
    2. The second model is named CustomerModel. The model contains the seven properties shown on the checkout page plus custID (see image to right). All properties are string except CustID which is int. Add Required validation to all fields and email validation to email. Add [Key] to CustId so that VS's view-builder puts in into a hidden form field.
    3. Database: Add a table named tblCustomers with fields matching the properties of CustomerModel (see image). CustID the primary key and autonumber (Identity).
    4. Controller: Create an HttpGet ActionResult named SignIn. It does nothing except return an empty view.
    5. View: Create a view named SignIn. Template is Create and model is SignInModel.
    6. Email field should be autofocus. EditorFor statements do not support autofocus so change it to a textbox with:

      @Html.TextBoxFor(model => model.Email, new { @class = "form-control" , autofocus = "autofocus" })

    7. Controller: Clicking the SignIn button causes the page to post to the server. The HttpPost handler validates the email, stores the email address in teh session, and redirects to the checkout view. The following shows how to check the validation. 
               [HttpPost]
              public ActionResult SignIn(SignInModel signInModel)
              {
                  if (!ModelState.IsValid) return View(signInModel);
                  
      
    8. Controller: Once email address is validated the user is redirected to the HttpGet checkout handler. Email address needs to be transferred to checkout so put email address in the Session. Then use RedirectToAction to redirect to the checkout handler. 
    9. Controller: The HttpGet Checkout handler uses email address to query the database to see if the user is new or returning. If returning it will populate the checkout form with user information, otherwise it only populates the email field. It also uses the ViewBag to display appropriate messages to the user. Create an HttpGet ActionMethod named Checkout and use the following syntax to retrieve email from the session:

      string email = Session["email"].ToString();

    10. DataRepository: The next step is to check the database to see if the customer is new or returning. Since the site is using two databases let's simplify matters by using two repositories. Create a new repository named MusicOrderRepository that uses your local database "Music". Create a method named GetPersonByEmail(string email) that searches tblCustomers for a matching email and returns a CustomerModel. In the controller instantiate a repository object named musicOrderRepository (lower case since this is a private object). The syntax for calling the method from the controller is:

      customerModel = musicOrderRepository.GetPersonByEmail(email);

    11. Controller: Use an if statement in the HttpPost SignIn handler to test if a matching email was found. customertModel will be null for a new user not null for a returning user. For new users we need to instantiate customerModel and add the email address as follows:
        if (customerModel != null)
            ViewBag.message = "Returning Customer: Please review shipping information";
        else
        {
            ViewBag.message = "New Customer: Please enter shipping information";
            customerModel = new CustomerModel();
            customerModel.Email = email;
        }                 
    12. The final step is to display the form by returning a view containing customerModel.
    13. View: Create a new view "Checkout" that uses the Edit template and CustomerModel. Add a @Viewbag.message tag to display the new/returning customer message.
    14. Controller: Create a HttpPost handler named checkout. This will validate and process the form data.
    15. MusicOrderRepository: The repository needs two additional methods, UpdateCustomer() and InsertCustomer. It is time consuming to these so you may use this code.
    16. In the HttpPost controller use an if statement to determine if the customer is new or returning. 
              [HttpPost]
              public ActionResult CheckOut(CustomerModel customerModel)
              {
                  if (!ModelState.IsValid) return View(customerModel);
                  //new or returning
                  if (customerModel.CustId > 0)
                  {
                     ...                    
      
    17. Complete the code snippet above by calling the update and insert repository methods. The InsertCustomer method returns the autonumber CustID from the database. Assign it to the customerModel as follows:

      //new customer customerModel.CustId = musicOrderRepository.InsertCustomer(customerModel);

    18. Test!
  3. In Assignment 9 you will complete the checkout process.


Submission instructions: Submit assignments via the Canvas course management system. Submit the full URL for each exercise in the assignment, listing the URLs in the same order that they are listed in the assignment. To minimize typos in URLs it is strongly recommended that you copy the URLs from the address bar of the browser rather than trying to type them. Incorrect URLs will not be graded and no credit will be given.

When pages are connected via navigation (as in your music store project) it is only necessary to submit the URL of the first page.

Regular Expressions HTML Color Names Color Picker ASCII Character Codes Unicode Character Codes