Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

Drag & Drop Shopping Cart Using ASP.NET MVC and JQuery

Rate me:
Please Sign up or sign in to vote.
4.76/5 (25 votes)
18 Dec 2011CPOL3 min read 174.8K   15.1K   79   43
Add interactivity to Shopping Cart Using JQuery and ASP.NET MVC

Introduction

In most E-commerce web applications, there are Add to Cart features provided using UI like button or link for add product into a cart. But a few days ago, I came across one good JQuery Shopping Cart Plug-in Example. It provides a feature like you can drag your product and drop into your shopping cart.

After seeing that example, I realized that it can be used to add more interactivity into Add to cart features of E-commerce Web Application. Then I decided to use that plug-in with ASP.NET MVC.

To keep this application simple, I have used just one table in database for display product List and am not covering any other feature like Add Products, etc.

Requirements

To implement this, there is a requirement of two JQuery files:

  1. JQuery-1.6.2
  2. JQuery-ui-1.8.11

You can download this file from Jquery.com or in case you are using VS2010 and MVC3 or MVC4 applications, then that jQuery File is already available in the script folder.

Implementation

app.JPG

The first step is to create a new MVC application in Visual Studio and check whether in script folder, both Jquery files are available or not. If not, then download that file and add files into the Script folder.

Now, create a database and add the below table named Products:

DB.JPG

After creating products table, insert records into tables for display products into the list page. For product image, store image name only in table and create one folder named images into the root level of project, then copy all images into that folder. After that, add connection string of database into webconfig file.

Now, for retrieving data from the database, I have creating one model class named Products into the Models Folder. Product model class code will look like below:

C#
public class Products
{
        public int ProductID ;
        public string ProductName;
        public decimal Price;
        public string ProductImage;
}

Now, create one new folder in the application root level named Data Access and one class into that folder named DALProducts. This class is used for the Direct Database Operation. Code of that class will look like below:

C#
public class DALProducts
   {
       public List<products> GetProductList()
       {
           SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings
               ["ProductDataBaseConnection"].ConnectionString);
           try
           {
               if (_con.State != System.Data.ConnectionState.Open)
                   _con.Open();
               SqlCommand _cmd = _con.CreateCommand();
               _cmd.CommandText = "Select * From Products";
               SqlDataReader _reader = _cmd.ExecuteReader();
               List<products> _lstPoducts = new List<products>();
               while (_reader.Read())
               {
                   Products _Products = new Products();
                   _Products.ProductID =Convert.ToInt32(_reader["ProductID"]);
                   _Products.ProductImage = _reader["ProductImage"].ToString();
                   _Products.ProductName = _reader["ProductName"].ToString();
                   _Products.Price = Convert.ToDecimal(_reader["Price"]);
                   _lstPoducts.Add(_Products);
               }
               return _lstPoducts;
           }
           catch (Exception ex)
           {
               throw ex;
           }
           finally
           {
               if (_con.State != System.Data.ConnectionState.Closed)
                   _con.Close();
           }
       }
   }

In the above code, GetProductList method returns a list of the products.

Add one controller into Controller folder named ProductController and add the below code into that:

C#
public class ProductController : Controller
{
      //
      // GET: /Product/
      public ActionResult Index()
      {
          DataAccess.DALProducts _obj = new DataAccess.DALProducts();
          return View(_obj.GetProductList());
      }
}

Here, in Index action of the controller, call GetproductList method of DALProduct class and pass list of the products into the view.

Add View name index.aspx at View/Product location and add the following markup into that file:

ASP.NET
<%@ Page Language="C#" Inherits="
System.Web.Mvc.ViewPage<IEnumerable<EcommerceApplication.Models.Products>>" %>
      <title>Index</title>
    <script type="text/javascript" src="../../Scripts/jquery-1.6.2.min.js"> </script>
    <script type="text/javascript" src="../../Scripts/jquery-ui-1.8.11.min.js"> </script>
    <style type="text/css">
        body
        {
            font-family: Arial, "Free Sans";
            margin: 0;
            padding: 0;
        }
        #main
        {
            background: #0099cc;
            margin-top: 0;
            padding: 2px 0 4px 0;
            text-align: center;
        }
        #main a
        {
            color: #ffffff;
            text-decoration: none;
            font-size: 12px;
            font-weight: bold;
            font-family: Arial;
        }
        #main a:hover
        {
            text-decoration: underline;
        }
        #item_container
        {
            width: 610px;
            margin: 0 auto;
            margin-top: 10px;
            margin-bottom: 10px;
        }
        .item
        {
            background: #fff;
            float: left;
            padding: 5px;
            margin: 5px;
            cursor: move;
            -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.5);
            -moz-box-shadow: 0 1px 2px rgba(0,0,0,.5);
            box-shadow: 0 1px 2px rgba(0,0,0,.5);
            -webkit-border-radius: .5em;
            -moz-border-radius: .5em;
            border-radius: .5em;
            z-index: 5;
        }
        .title, .price
        {
            display: block;
            text-align: center;
            font-size: 14px;
            letter-spacing: -1px;
            font-weight: bold;
            cursor: move;
        }
        .title
        {
            color: #333;
        }
        .price
        {
            color: #0099cc;
            margin-top: 5px;
            -webkit-border-radius: .5em;
            -moz-border-radius: .5em;
            border-radius: .5em;
        }
        .icart, .icart label
        {
            cursor: e-resize;
        }
        .divrm
        {
            text-align: right;
        }
        .remove
        {
            text-decoration: none;
            cursor: pointer;
            font-weight: bold;
            font-size: 20px;
            position: relative;
            top: -7px;
        }
        .remove:hover
        {
            color: #999;
        }
        .clear
        {
            clear: both;
        }
        #cart_container
        {
            margin: 0 auto;
            width: 495px;
        }
        #cart_title span
        {
            border: 8px solid #666;
            border-bottom-width: 0;
            background: #333;
            display: block;
            float: left;
            color: #fff;
            font-size: 11px;
            font-weight: bold;
            padding: 5px 10px;
            -webkit-border-radius: .5em .5em 0 0;
            -moz-border-radius: .5em .5em 0 0;
            border-radius: .5em .5em 0 0;
        }
        #cart_toolbar
        {
            overflow: hidden;
            border: 8px solid #666;
            height: 190px;
            z-index: -2;
            width: 483px;
            -webkit-border-radius: 0 .5em 0 0;
            -moz-border-radius: 0 .5em 0 0;
            border-radius: 0 .5em 0 0;
            background: #ffffff;
        }
        #cart_items
        {
            height: 190px;
            width: 483px;
            position: relative;
            padding: 0 0 0 2px;
            z-index: 0;
            cursor: e-resize;
            border-width: 0 2px;
        }
        .back
        {
            background: #e9e9e9;
        }
        #navigate
        {
            width: 463px;
            margin: 0 auto;
            border: 8px solid #666;
            border-top-width: 0;
            -webkit-border-radius: 0 0 .5em .5em;
            -moz-border-radius: 0 0 .5em .5em;
            border-radius: 0 0 .5em .5em;
            padding: 10px;
            font-size: 14px;
            background: #333;
            font-weight: bold;
        }
        #nav_left
        {
            float: left;
        }
        #nav_left a
        {
            padding: 4px 8px;
            background: #fff;
            -webkit-border-radius: .5em;
            -moz-border-radius: .5em;
            border-radius: .5em;
            text-decoration: none;
            color: #0099cc;
        }
        #nav_left a:hover
        {
            background: #666;
            color: #fff;
        }
        #nav_right
        {
            float: right;
        }
        .sptext
        {
            background: #ffffff;
            padding: 4px 8px;
            margin-left: 8px;
            -webkit-border-radius: .5em;
            -moz-border-radius: .5em;
            border-radius: .5em;
            color: #666;
        }
        .count
        {
            color: #0099cc;
        }
        .drop-active
        {
            background: #ffff99;
        }
        .drop-hover
        {
            background: #ffff66;
        }
    </style>
    <script type="text/javascript">
        var total_items = 0;
        var total_price = 0;
        $(document).ready(function () {

            $(".item").draggable({
                revert: true
            });
            $("#cart_items").draggable({
                axis: "x"
            });

            $("#cart_items").droppable({
                accept: ".item",
                activeClass: "drop-active",
                hoverClass: "drop-hover",
                drop: function (event, ui) {
                    var item = ui.draggable.html();
                    var itemid = ui.draggable.attr("id");
                    var html = '<div class="item icart">';
                    html = html + '<div class="divrm">';
                    html = html + '<a onclick="remove(this)" 
                class="remove ' + itemid + '">×</a>';
                    html = html + '<div/>' + item + '</div>';
                    $("#cart_items").append(html);

                    // update total items
                    total_items++;
                    $("#citem").html(total_items);

                    // update total price
                    var price = parseInt(ui.draggable.find
                (".price").html().replace("$ ", ""));
                    total_price = total_price + price;
                    $("#cprice").html("$ " + total_price);

                    // expand cart items
                    if (total_items > 4) {
                        $("#cart_items").animate({ width: "+=120" }, 'slow');
                    }
                }
            });

            $("#btn_next").click(function () {
                $("#cart_items").animate({ left: "-=100" }, 100);
                return false;
            });
            $("#btn_prev").click(function () {
                $("#cart_items").animate({ left: "+=100" }, 100);
                return false;
            });
            $("#btn_clear").click(function () {
                $("#cart_items").fadeOut("2000", function () {
                    $(this).html("").fadeIn("fast").css({ left: 0 });
                });
                $("#citem").html("0");
                $("#cprice").html("$ 0");
                total_items = 0;
                total_price = 0;
                return false;
            });
        });
        function remove(el) {
            $(el).hide();
            $(el).parent().parent().effect("highlight", { color: "#ff0000" }, 1000);
            $(el).parent().parent().fadeOut('1000');
            setTimeout(function () {
                $(el).parent().parent().remove();
                // collapse cart items
                if (total_items > 3) {
                    $("#cart_items").animate({ width: "-=120" }, 'slow');
                }
            }, 1100);

            // update total item
            total_items--;
            $("#citem").html(total_items);

            // update totl price
            var price = parseInt($(el).parent().parent().
            find(".price").html().replace("$ ", ""));
            total_price = total_price - price;
            $("#cprice").html("$ " + total_price);
        }
       
    <div id="item_container">
     <% foreach (var item in Model)
           { %>
          <div id="i<%:item.ProductID %>" class="item">
              <img src="%3C%:%20Url.Content%28" />"/>
              <label class="title"><%:item.ProductName%></label>
              <label class="price">$ <%:item.Price %></label>
          </div>
         <% } %>
          <div class="clear"> </div>
      </div>
    <div id="cart_container">
          <div id="cart_title">
              <span>Shopping Cart </span>
              <div class="clear"></div>
          </div>
          <div id="cart_toolbar">
              <div class="back" id="cart_items"></div>
          </div>
          <div id="navigate">
              <div id="nav_left">
                  <a id="btn_prev"><</a>
                  <a id="btn_next">></a>
                  <a id="btn_clear">Clear Cart</a>
              </div>
              <div id="nav_right">
                  <span class="sptext">
                      <label>Items </label><label id="citem" class="count">0</label>
                  </span>
                  <span class="sptext">
                      <label>Price </label><label id="cprice" class="count">$ 0</label>
                  </span>
              </div>
              <div class="clear"></div>
          </div>
      </div>
</body>
</html>

In the above markup, to generate products list we iterate over product models. It will display product name, images and price of that products.

Now run the application and type URL into the browser like http://localhost/Product/. You will get a screen similar to screen shot and drag any product from the product list and add into the cart. You will notice that when you add products into cart, it will automatically add their price into the total amount and number of the items. You can navigate into the Cart and also clear the whole cart using clear Cart button. You can remove a single product using click on the close image on the product images. When you remove single product at that time, it will deduct that price from the Total Amount and decrease one product into total number of the products.

Conclusion

I've been using this plug-in to provide more interactivity to the end user for E-Commerce application. Hopefully, you'll find this as useful as I have found it for my code.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I have been working as a Software Engineer on Microsoft .NET Technology.I have developed several web/desktop application build on .NET technology .My point of interest is Web Development,Desktop Development,Ajax,Json,Jquey,XML etc.I have completed Master of Computer Application in May-2011.I'm not happy unless I'm learning something new.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Arkitec14-Jul-17 21:13
professionalArkitec14-Jul-17 21:13 
QuestionNot understand the img tag src ?? Pin
Dharmesh .S. Patil15-Jun-15 20:38
professionalDharmesh .S. Patil15-Jun-15 20:38 
Bugthere will be missing end script in Index.aspx Pin
Dharmesh .S. Patil15-Jun-15 19:59
professionalDharmesh .S. Patil15-Jun-15 19:59 
QuestionVery nice article Pin
Member 102366824-Jan-15 22:36
professionalMember 102366824-Jan-15 22:36 
QuestionHow Get items ID?? Pin
wolfre29-Oct-14 16:01
wolfre29-Oct-14 16:01 
GeneralMy vote of 5 Pin
syed shanu25-Aug-13 15:07
mvasyed shanu25-Aug-13 15:07 
QuestionConnectionstring Pin
Member 1000653016-May-13 9:57
Member 1000653016-May-13 9:57 
GeneralMy vote of 5 Pin
BishoyWasfy17-Feb-13 3:52
BishoyWasfy17-Feb-13 3:52 
fabulous
GeneralMy vote of 5 Pin
Renju Vinod18-Dec-12 0:19
professionalRenju Vinod18-Dec-12 0:19 
GeneralMy vote of 5 Pin
Unque9-Oct-12 4:59
Unque9-Oct-12 4:59 
QuestionDrag and drop the images Pin
Rani khandre13-Aug-12 0:43
Rani khandre13-Aug-12 0:43 
QuestionQuery Pin
Member 93381906-Aug-12 4:21
Member 93381906-Aug-12 4:21 
AnswerRe: Query Pin
Jigar Bagadai6-Aug-12 6:19
Jigar Bagadai6-Aug-12 6:19 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey7-Jul-12 2:05
professionalManoj Kumar Choubey7-Jul-12 2:05 
Questionusing the cart with json Pin
shivnaresh18-Jun-12 7:11
shivnaresh18-Jun-12 7:11 
QuestionAbout shopping cart Pin
akashs.cse28-Mar-12 9:36
akashs.cse28-Mar-12 9:36 
GeneralMy vote of 5 Pin
Rolf Cerff20-Feb-12 7:47
Rolf Cerff20-Feb-12 7:47 
QuestionMVC drag and drop handler Pin
Member 850069024-Dec-11 2:24
Member 850069024-Dec-11 2:24 
AnswerRe: MVC drag and drop handler Pin
Jigar Bagadai27-Dec-11 19:05
Jigar Bagadai27-Dec-11 19:05 
GeneralRe: MVC drag and drop handler Pin
Member 850069027-Dec-11 19:25
Member 850069027-Dec-11 19:25 
GeneralRe: MVC drag and drop handler Pin
Member 850069029-Dec-11 3:25
Member 850069029-Dec-11 3:25 
GeneralMy vote of 5 Pin
Monjurul Habib21-Dec-11 6:35
professionalMonjurul Habib21-Dec-11 6:35 
GeneralRe: My vote of 5 Pin
Jigar Bagadai27-Dec-11 19:06
Jigar Bagadai27-Dec-11 19:06 
GeneralMy vote of 5 Pin
MikaHaki20-Dec-11 20:19
MikaHaki20-Dec-11 20:19 
GeneralRe: My vote of 5 Pin
Jigar Bagadai20-Dec-11 22:01
Jigar Bagadai20-Dec-11 22:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.