65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ASP.NET MVC 和 JQuery 的拖放购物车

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (23投票s)

2011年12月17日

CPOL

3分钟阅读

viewsIcon

187856

downloadIcon

15122

使用 JQuery 和 ASP.NET MVC 为购物车添加交互性

引言

在大多数电子商务 Web 应用程序中,都提供了使用 UI(如按钮或链接)添加到购物车的功能,以便将产品添加到购物车。但几天前,我遇到了一个很好的 JQuery 购物车插件示例。它提供了一个您可以拖动产品并将其拖放到购物车的特性。

在看到那个例子之后,我意识到它可用于在电子商务 Web 应用程序的“添加到购物车”功能中添加更多交互性。然后我决定将该插件与 ASP.NET MVC 一起使用。

为了保持此应用程序的简单性,我只在数据库中使用了单个表来显示产品列表,并且没有涵盖任何其他功能,例如添加产品等。

要求

要实现这一点,需要两个 JQuery 文件

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

您可以从 Jquery.com 下载此文件,或者如果您使用 VS2010 和 MVC3 或 MVC4 应用程序,则该 jQuery 文件已在 *script* 文件夹中可用。

实现

app.JPG

第一步是在 Visual Studio 中创建一个新的 MVC 应用程序,并检查 *script* 文件夹中是否有这两个 Jquery 文件。如果没有,则下载该文件并将文件添加到 *Script* 文件夹中。

现在,创建一个数据库并添加以下名为 Products 的表

DB.JPG

创建 products 表后,将记录插入表中以在列表页面中显示产品。对于产品图像,仅在表中存储图像名称,并在项目的根级别创建一个名为 *images* 的文件夹,然后将所有图像复制到该文件夹中。之后,将数据库的连接字符串添加到 *webconfig* 文件中。

现在,为了从数据库中检索数据,我创建了一个名为 Productsmodel 类,放入了 *Models* 文件夹中。 Product 模型类代码如下所示

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

现在,在应用程序根级别创建一个名为 Data Access 的新文件夹,并将一个名为 DALProducts 的类放入该文件夹中。此类用于直接数据库操作。该类的代码如下所示

 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();
            }
        }
    }

在上面的代码中,GetProductList 方法返回产品列表。

Controller 文件夹中添加一个名为 ProductController 的控制器,并将以下代码添加到其中

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

在这里,在控制器的 Index 操作中,调用 DALProduct 类的 GetproductList 方法,并将产品列表传递给视图。

在 View/Product 位置添加视图名称 index.aspx,并将以下标记添加到该文件中

<%@ 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>

在上面的标记中,为了生成产品列表,我们迭代了产品模型。它将显示产品名称、图像和价格。

现在运行应用程序,并在浏览器中输入 URL,例如 https:///Product/。您将获得一个类似于屏幕截图的屏幕,并从产品列表中拖动任何产品并将其添加到购物车中。您会注意到,当您将产品添加到购物车时,它将自动将它们的价格添加到总金额和商品数量中。您可以在购物车中导航,也可以使用清空购物车按钮清空整个购物车。您可以使用单击产品图像上的关闭图像来删除单个产品。当您删除单个产品时,它将从总金额中扣除该价格,并将总产品数量减少一个。

结论

我一直在使用此插件为电子商务应用程序的最终用户提供更多交互性。希望您会发现它对您的代码也很有用。

参考

© . All rights reserved.