Click here to Skip to main content
15,867,568 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

 
QuestionMVC Pin
Member 850069020-Dec-11 4:12
Member 850069020-Dec-11 4:12 
AnswerRe: MVC Pin
Jigar Bagadai20-Dec-11 15:47
Jigar Bagadai20-Dec-11 15:47 
GeneralRe: MVC Pin
Member 850069020-Dec-11 19:19
Member 850069020-Dec-11 19:19 
GeneralRe: MVC Pin
Jigar Bagadai20-Dec-11 20:05
Jigar Bagadai20-Dec-11 20:05 
GeneralRe: MVC Pin
Member 850069020-Dec-11 22:46
Member 850069020-Dec-11 22:46 
GeneralRe: MVC Pin
Member 850069020-Dec-11 22:40
Member 850069020-Dec-11 22:40 
GeneralRe: MVC Pin
Jigar Bagadai21-Dec-11 0:49
Jigar Bagadai21-Dec-11 0:49 
GeneralRe: MVC Pin
Member 850069021-Dec-11 22:10
Member 850069021-Dec-11 22:10 
QuestionMVC 3 Pin
Member 850069019-Dec-11 8:14
Member 850069019-Dec-11 8:14 
AnswerRe: MVC 3 Pin
Jigar Bagadai19-Dec-11 15:35
Jigar Bagadai19-Dec-11 15:35 
GeneralRe: MVC 3 Pin
Member 850069019-Dec-11 21:46
Member 850069019-Dec-11 21:46 
GeneralRe: MVC 3 Pin
Jigar Bagadai19-Dec-11 22:20
Jigar Bagadai19-Dec-11 22:20 
QuestionMVC3 Pin
Member 850069019-Dec-11 4:16
Member 850069019-Dec-11 4:16 
AnswerRe: MVC3 Pin
Member 850069019-Dec-11 4:20
Member 850069019-Dec-11 4:20 
GeneralRe: MVC3 Pin
Jigar Bagadai19-Dec-11 5:34
Jigar Bagadai19-Dec-11 5:34 
GeneralRe: MVC3 Pin
Jigar Bagadai19-Dec-11 5:55
Jigar Bagadai19-Dec-11 5:55 
GeneralMy vote of 5 Pin
maq_rohit17-Dec-11 23:38
professionalmaq_rohit17-Dec-11 23:38 
GeneralRe: My vote of 5 Pin
Jigar Bagadai18-Dec-11 1:27
Jigar Bagadai18-Dec-11 1:27 

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.