Creating Shopping Cart Application From Scratch In MVC - Part Two

Introduction

In online marketing, a shopping cart is a piece of e-commerce software running on a web server, that allows visitors to an Internet shop to select items for eventual purchase, analogous to the American English term "shopping cart." In British English, it is generally known as a shopping basket, almost exclusively shortened on websites to "basket".

The software allows online shopping customers to accumulate a list of items for purchase, described metaphorically as “placing items in the shopping cart” or “add to cart.” Upon checkout, the software typically calculates a total for the order, including shipping and handling (i.e., postage and packing) charges and the associated taxes, as applicable.

This article describes the implementation of a shopping cart using MVC and jQuery.

Prerequisites
  1. General knowledge on web applications.
  2. HTML, CSS, Bootstrap, JavaScript.
  3. Database Configuration and Connection.
Agenda
  1. Displaying product details from the database.
  2. Showing particular product details from database.
  3. Implementing Zoom effect for products.
  4. Adding selected item to the shopping cart.
  5. Showing all recently added cart items.
  6. Removing items from a cart.
In our previous section, we have learned how to start creating the shopping cart application. There we learned about creating the project with different layers, basic flow, creating basic Layouts, etc. You can find the link here.
 


In this section, we will learn adding a full description to each product from database. Here is the code to show the full description of the product in the View.
  1. @model IEnumerable < DapperProject.Models.ProductDetails > @ {  
  2.     ViewBag.Title = "EachProductDetails";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. } < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script>   < link rel = "stylesheet"  
  5. href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" > < /script>   < script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script>    
  6.     /* #####################################################################  
  7.       #  
  8.       #   Project       : MOBBI99  
  9.       #   Author        : Debendra Dash  
  10.       #   Version       : 1.0  
  11.       #   Created       : 02/12/2016  
  12.       #     
  13.       #  
  14.       ##################################################################### */  
  15.     < /style>   < h3 > Product Specification < /h3>   < div ng - controller = "MainCtrl" > @foreach(var x in Model) { < div class = "panel panel-default" > < div class = "panel-heading" > @x.MobileName < /div>   < div class = "panel-body" > < div class = "col-sm-3 col-md-6"  
  16.         style = "color:blue" > < img src = "~/Images/@x.Url"  
  17.         width = "400"  
  18.         height = "400" / > < /div>   < div class = "col-sm-9 col-md-6" > < h3 > < span id = "mobilename"  
  19.         style = "color:black" > < b > MobileName: < /b></span > < /h3>   < h6 > < span id = "mobilename"  
  20.         style = "color:black" > @x.MobileName < /span></h  
  21.         6 > < h3 > < span id = "mobilename"  
  22.         style = "color:black" > < b > Features: < /b></span > < /h3>   < h6 > < span id = "mobilename"  
  23.         style = "color:black" > @x.Features < /span></h  
  24.         6 > < h3 > < span id = "mobilename"  
  25.         style = "color:black" > < b > Color: < /b></span > < /h3>   < h4 > < span id = "mobilename"  
  26.         style = "color:black" > @x.color < /span></h  
  27.         4 > < h3 > < span id = "mobilename"  
  28.         style = "color:black" > < b > Sim Type < /b></span > < /h3>   < h4 > < span id = "mobilename"  
  29.         style = "color:black" > @x.SimType < /span></h  
  30.         4 > < h3 > < span id = "mobilename"  
  31.         style = "color:black" > < b > Model: < /b></span > < /h3>   < h6 > < span id = "mobilename"  
  32.         style = "color:black" > @x.model < /span></h  
  33.         6 > < h3 > < span id = "mobilename"  
  34.         style = "color:black" > < b > Price: < /b></span > < /h3>   < h6 > < span id = "mobilename"  
  35.         style = "color:black" > @x.Price < /span></h  
  36.         6 > < /div>   < /div>   < div > < a id = "btn_add"  
  37.         href = "@Url.Action("  
  38.         Add ", "  
  39.         AddToCart ",x)"  
  40.         class = "btn btn-info btn-lg"  
  41.         style = "margin-left:60px" > < span class = "glyphicon glyphicon-shopping-cart" > < /span> Add To Cart   < /a>   < a id = "btn_add"  
  42.         href = "@Url.Action("  
  43.         Index ", "  
  44.         Home ")"  
  45.         class = "btn btn-info btn-lg"  
  46.         style = "margin-left:60px" > < span class = "glyphicon glyphicon-eye-open" > < /span> Continue shopping   < /a>   < br / > < /div>   < /div>    
  47.     } < /div>  
So, here is our ProductDetails model.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace DapperProject.Models {  
  6.     public class ProductDetails {  
  7.         public int ? slno {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string MobileName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public double Price {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Url {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string Features {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string model {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public string color {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         public string SimType {  
  36.             get;  
  37.             set;  
  38.         }  
  39.     }  
  40. }  
Here is the model for mobile. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace DapperProject.Models {  
  6.     public class Mobiles {  
  7.         public int ? slno {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string MobileName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public double Price {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Url {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string ZoomUrl {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string Description {  
  28.             get;  
  29.             set;  
  30.         }  
  31.     }  
  32. }  
This is the script of the table.
  1. USE[Demo]  
  2. GO  
  3. /****** Object: Table [dbo].[MobileDetails] Script Date: 03-12-2016 10:33:24 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE[dbo].[MobileDetails](  
  9.     [SLNO][int] IDENTITY(1, 1) NOT NULL, [MobileId][int] NULL, [Features][nvarchar](600) NULL, [Model][nvarchar](50) NULL, [Color][nvarchar](50) NULL, [SimType][nvarchar](50) NULL, CONSTRAINT[PK_MobileDetails] PRIMARY KEY CLUSTERED(  
  10.         [SLNO] ASC) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]) ON[PRIMARY]  
  11. GO  
  12. ALTER TABLE[dbo].[MobileDetails] WITH CHECK ADD CONSTRAINT[FK_MobileDetails_Mobiles] FOREIGN KEY([MobileId])  
  13. REFERENCES[dbo].[Mobiles]([slNo])  
  14. GO  
  15. ALTER TABLE[dbo].[MobileDetails] CHECK CONSTRAINT[FK_MobileDetails_Mobiles]  
  16. GO  
And, this is my table data for showing in details page.



Now, given below is the Controller logic to get the data.
  1. public ActionResult EachProductDetails(Mobiles m)  
  2.         {  
  3.               
  4.             string mycmd = "select m.slNo,m.MobileName,m.price,m.url,md.Features,md.model,md.color,md.SimType from mobiles m inner join MobileDetails md on m.slNo=md.MobileId where m.slNo="+m.slno+"";  
  5.             dt = new DataTable();  
  6.   
  7.             dt = _mdal.SelactAll(mycmd);  
  8.   
  9.   
  10.             List<ProductDetails> list = new List<ProductDetails>();  
  11.   
  12.             for (int i = 0; i < dt.Rows.Count; i++)  
  13.             {  
  14.                 ProductDetails mob = new ProductDetails();  
  15.                 mob.slno = Convert.ToInt32(dt.Rows[i]["slNo"]);  
  16.                 mob.MobileName = dt.Rows[i]["MobileName"].ToString();  
  17.                 mob.Price = Convert.ToDouble(dt.Rows[i]["Price"]);  
  18.                 mob.Url = dt.Rows[i]["Url"].ToString();  
  19.                 mob.Features= dt.Rows[i]["Features"].ToString();  
  20.                 mob.color = dt.Rows[i]["color"].ToString();  
  21.                 mob.SimType = dt.Rows[i]["SimType"].ToString();  
  22.   
  23.                 list.Add(mob);  
  24.             }  
  25.              
  26.             
  27.             return View(list);  
  28.   
  29.              
  30.   
  31.         }  
Here is our MobileDAL.cs  class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Data;  
  7. using System.Configuration;  
  8. using System.Data.SqlClient;  
  9. namespace MobileDAL.cs {  
  10.     public class MobiledetailDAL {  
  11.         SqlCommand cmd;  
  12.         SqlDataAdapter da;  
  13.         DataSet ds;  
  14.         public static SqlConnection connect() {  
  15.             string connection = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;  
  16.             SqlConnection con = new SqlConnection(connection);  
  17.             if (con.State == ConnectionState.Open) {  
  18.                 con.Close();  
  19.             } else {  
  20.                 con.Open();  
  21.             }  
  22.             return con;  
  23.         }  
  24.         public bool DMLOpperation(string query) {  
  25.             cmd = new SqlCommand(query, MobiledetailDAL.connect());  
  26.             int x = cmd.ExecuteNonQuery();  
  27.             if (x == 1) {  
  28.                 return true;  
  29.             } else {  
  30.                 return false;  
  31.             }  
  32.         }  
  33.         public DataTable SelactAll(string query) {  
  34.             da = new SqlDataAdapter(query, MobiledetailDAL.connect());  
  35.             DataTable dt = new DataTable();  
  36.             da.Fill(dt);  
  37.             return dt;  
  38.         }  
  39.     }  
  40. }  
Now, just run the project. It will show the following output.



Now, we will check the zoom functionality of the selected image in the detail View. For working with the zoom functionality, we need to use some jQuery plugin. In this case, I have tried AngularJS for zoom functionality.

So, just change the image div as follow.
  1. <div class="col-sm-3 col-md-6" style="color:blue">  
  2.                     <a href="http://localhost:56829/ZoomImages/@x.Url" class="cloud-zoom" rel="adjustX: 10, adjustY:-4">  
  3.                         <img src="~/Images/@x.Url" width="400" height="400" />  
  4.                     </a>  
  5.   
  6.                 </div>  
Use the following scripts in the head section.
  1. <link rel="stylesheet" href="style.css">  
  2. <link href="http://www.professorcloud.com/styles/cloud-zoom.css" rel="stylesheet" type="text/css">  
  3. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>  
  5. <script type="text/JavaScript" src="http://www.professorcloud.com/js/cloud-zoom.1.0.2.js"></script>  
  6. <script src="~/Scripts/app.js"></script>  
To know more about this Zoom functionality, please visit the site here
 
Now, save the project and run it. You will find the following zoom effect.



Let's start to work with the product in the shopping cart. Here is my design for the Product Specification page.
 

  1. <div>  
  2.   
  3.     <a  id="btn_add" href="@Url.Action("Add", "AddToCart",x)" class="btn btn-info btn-lg" style="margin-left:60px">  
  4.         <span class="glyphicon glyphicon-shopping-cart"></span> Add To Cart  
  5.     </a>  
  6.   
  7.     <a id="btn_add" href="@Url.Action("Index", "Home")" class="btn btn-info btn-lg" style="margin-left:60px">  
  8.         <span class="glyphicon glyphicon-eye-open"></span> Continue shopping  
  9.     </a>  
  10.     <br />  
  11.     <br />  
  12.   
  13. </div>  
And for adding items to the cart, we have created a Controller as AddToCart, where we have an action method as Add. On the button click of Addtocart, we are sending all the information of that particular Controller to the action method. Please check the full View HTML code which is shown above. This is only one portion of the View.
 
Finally, we are sending all the details of the clicked product to the Controller. Here is my Controller Add method.
  1. public class AddToCartController : Controller  
  2.    {  
  3.        DataTable dt;  
  4.        MobiledetailDAL _mdal = new MobiledetailDAL();  
  5.        // GET: AddToCart  
  6.        public ActionResult Add( Mobiles mo)  
  7.        {  
  8.              
  9.            if (Session["cart"]==null)  
  10.            {  
  11.                List<Mobiles> li = new List<Mobiles>();  
  12.   
  13.                li.Add(mo);  
  14.                Session["cart"] = li;  
  15.                ViewBag.cart = li.Count();  
  16.   
  17.                 
  18.                    Session["count"] = 1;  
  19.   
  20.   
  21.            }  
  22.            else  
  23.            {  
  24.                List<Mobiles> li = (List<Mobiles>)Session["cart"];  
  25.                li.Add(mo);  
  26.                Session["cart"] = li;  
  27.                ViewBag.cart = li.Count();  
  28.                Session["count"] = Convert.ToInt32(Session["count"]) + 1;  
  29.   
  30.            }  
  31.            return RedirectToAction("Index""Home");  
  32.   
  33.             
  34.        }  

So, to add the product to the cart, we are basically following 4 important steps.
  1. Creating a session "Session["cart"]" which is null for the first time, for all users.

  2. If the cart is null, creating a list of mobile types, saving the mobile details coming through the parameter of a view, and assigning them to the session.

  3. Creating another session Session["count"] for counting the product added in the cart.

  4. Similarly, if the "Session["cart"] is not null, then adding one more list item to the session and increasing the counter as per the number of products added.
So, after adding the product to the cart, I am redirecting the user to the shopping page.



Here is the code which will update the product count in the layout. 
  1. <ul class="nav navbar-nav">  
  2.           <li class="active"><a href="@Url.Action("Myorder", "AddToCart")" class="btn btn-info btn-lg">  
  3.   <span class="glyphicon glyphicon-shopping-cart" style="color:green"></span>Cart <span class="badge">@Session["count"]</span>  
  4. t;/a>  
Now it will appear like this.



To check all the items in the cart, we have the following  Myorder method.
  1.        public ActionResult Myorder()  
  2.         {  
  3.               
  4.             return View((List<Mobiles>)Session["cart"]);  
  5.   
  6.         }  
Here, we just return the data of the session to the View. The code of the view is given below.

  1. @model IEnumerable < DapperProject.Models.Mobiles > @ {  
  2.     ViewBag.Title = "Myorder";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5. @ {  
  6.     int sum = 0;  
  7. } < link rel = "stylesheet"  
  8. href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" > < /script>   < script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script>   < div id = "dvContents" > < table class = "table table-hover"  
  9. width = "100%" > < thead > < img src = "~/Templates/Header.jpg"  
  10. width = "100%"  
  11. height = "70px" / > < tr > < th > SlNO < /th>   < th > Mobile Name < /th>   < th > Image < /th>   < th > Price < /th>   < th > Remove < /th>   < /tr>   < /thead>   < tbody > @foreach(var x in Model) { < tr > < td > @x.slno < /td>   < td > @x.MobileName < /td>   < td > < img id = "img1"  
  12.     src = "~/Images/@x.Url"  
  13.     height = "100"  
  14.     width = "75" / > < /td>   < td > ₹@x.Price < /td>   < td > < button id = "btn_delete"  
  15.     class = "label label-primary"  
  16.     data - slno = "@x.slno"  
  17.     onclick = "location.href='@Url.Action("  
  18.     Remove ","  
  19.     AddToCart ",x)'" > < img src = "~/Icons/delete.png"  
  20.     height = "30"  
  21.     width = "30" / > < /button>   < /td>   < /tr>    
  22. } < /tbody>    
  23. @foreach(var x in Model) {  
  24.     sum = Convert.ToInt32(x.Price) + sum;  
  25. } < tfoot > < tr > < td > < /td>   < td > < /td>   < td > < b > Total < /b></td > < td > ₹@sum < /td>   < /tr>   < /tfoot>   < /table>   < div id = "footer" > < img src = "~/Templates/Footer.jpg"  
  26. width = "100%"  
  27. height = "60px" / > < /div>   < button type = "button"  
  28. id = "btnPrint"  
  29. class = "btn btn-primary" > Print < /button>   < button type = "button"  
  30. class = "btn btn-success" > Continue Shopping < /button>   < button type = "button"  
  31. class = "btn btn-warning" > Place Order < /button>   < /div>  
 
Now, if we want to remove any item from cart, here is the code.
  1. <td>  
  2.   
  3.   
  4.                        <button id="btn_delete" class="label label-primary" data-slno="@x.slno" onclick="location.href='@Url.Action("Remove","AddToCart",x)'">  
  5.                            <img src="~/Icons/delete.png" height="30" width="30" />  
  6.                        </button>  
Method for removing items from the cart.
  1. public ActionResult Remove(Mobiles mob)  
  2.        {  
  3.            List<Mobiles> li = (List<Mobiles>)Session["cart"];  
  4.            li.RemoveAll(x=>x.slno==mob.slno);  
  5.            Session["cart"] = li;  
  6.            Session["count"] = Convert.ToInt32(Session["count"]) - 1;  
  7.            return RedirectToAction("Myorder""AddToCart");  
  8.             
  9.        }  


If you want to print the order sheet, here is the JavaScript code that will print the invoice.
  1. <style type="text/css">  
  2.     .label {  
  3.         -size: 10pt;  
  4.         -weight: bold;  
  5.         -family: Arial;  
  6.     }  
  7.       
  8.     .contents {  
  9.         border: 1px dotted black;  
  10.         padding: 5px;  
  11.         width: 300px;  
  12.     }  
  13.       
  14.     .name {  
  15.         color: #18B5F0;  
  16.     }  
  17.       
  18.     .left {  
  19.         float: left;  
  20.         width: 50px;  
  21.         height: 50px;  
  22.     }  
  23.       
  24.     .right {  
  25.         margin-left: 60px;  
  26.         line-height: 50px;  
  27.     }  
  28.       
  29.     .clear {  
  30.         clear: both;  
  31.     }  
  32.      
  33.     #footer {  
  34.         position: fixed;  
  35.         bottom: 0px;  
  36.         height: 3px;  
  37.         background-color: #666;  
  38.         color: #eee;  
  39.         width: 100%  
  40.     }  
  41. </style>  
  42. <script type="text/javascript">  
  43.     $(function() {  
  44.         $("#btnPrint").click(function() {  
  45.             var contents = $("#dvContents").html();  
  46.             var frame1 = $('<iframe />');  
  47.             frame1[0].name = "frame1";  
  48.             frame1.css({  
  49.                 "position""absolute",  
  50.                 "top""-1000000px"  
  51.             });  
  52.             $("body").append(frame1);  
  53.             var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;  
  54.             frameDoc.document.open();  
  55.             //Create a new HTML document.    
  56.             frameDoc.document.write('<html><head><title>DIV Contents</title>');  
  57.             frameDoc.document.write('</head><body>');  
  58.             //Append the external CSS file.    
  59.             frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');  
  60.             //Append the DIV contents.    
  61.             frameDoc.document.write(contents);  
  62.             frameDoc.document.write('</body></html>');  
  63.             frameDoc.document.close();  
  64.             setTimeout(function() {  
  65.                 window.frames["frame1"].focus();  
  66.                 window.frames["frame1"].print();  
  67.                 frame1.remove();  
  68.             }, 500);  
  69.         });  
  70.     });  
  71. </script>  
This will print the complete report structure inside the  "dvcontents" div.

 
So, in this way, we can create a simple shopping cart application. If you have any doubts regarding this, please let me know.

Download Source Code

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now