购物车未添加正确数量的EF 6 MVC 5

时间:2015-07-25 17:43:26

标签: asp.net-mvc-5 entity-framework-6

我知道我最近问了很多问题,为此我道歉,我正在学习MVC的细节。无论如何,当我选择一个数量并点击添加到购物车时,它不会添加我选择的数量,几乎就像它只是抓取一个随机数并添加它。这是视图的代码:

 @model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>

@{
    ViewBag.Title = "Products > Necklaces";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
    @Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))
{
    <div id="container">
        <div class="scroll">

            @foreach (var item in Model)
            {
                <div class="scroll">
                    <div class="itemcontainer">
                        <table>
                            <tr>
                                <td id="@item.Id">
                                    <div class="DetailsLink"> &nbsp;&nbsp;&nbsp;@Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
                                    <br />
                                    <div id="@item.Id"></div>
                                    <div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
                                    <div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
                                    <div>&nbsp;</div>
                                    <div class="divQuantity">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @id = "quantity", @style = "width:50px;", @class = "formTextBox" })</div>
                                    <div class="divAddToCart">
                                        <p class="button">
                                            @Html.ActionLink("Add to cart", "AddToCart", "Orders", new { id = item.Id }, new { @class = "AddToCart" })
                                        </p>
                                    </div>
                                    <div style="height:15px;"></div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                    }
                    <div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
                    <br />
       </div>        
    </div>
}
@section scripts {
    <script src="~/Scripts/jQuery-jScroll.js"></script>
    <script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
    <script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
    <script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
    <script type="text/javascript">
            //$(function () {
            //    $('.scroll').jscroll({
            //        autoTrigger: true
            //    });
                $('.fancybox-thumbs').fancybox({
                    prevEffect: 'none',
                    nextEffect: 'none',

                    closeBtn: true,
                    arrows: false,
                    nextClick: false
                });
            });
    </script>
}

以下是我的控制器中 AddToCart 的代码:

// GET: /Orders/AddToCart/5
public ActionResult AddToCart(int id)
{
    // Retrieve the product from the database
    var productAdded = db.Products
        .Single(p => p.ProductId == id);

    // Add it to the shopping cart
    var cart = ShoppingCart.GetCart(this.HttpContext);

    cart.AddToCart(productAdded);

    // Go back to the main store page for more shopping
    return RedirectToAction("Index");
}

最后, ShoppingCart 模型中 AddToCart 的代码:

 public void AddToCart(Product item)
    {
        // Get the matching cart and product instances
        var order = entities.Orders.FirstOrDefault(
            c => c.OrderGUID == ShoppingCartId
            && c.OrderItems.Where(p=>p.ProductId == item.ProductId).FirstOrDefault().ProductId == item.ProductId);

        if (order == null)
        {
            // Create a new order since one doesn't already exist
            order = new Order
            {
                InvoiceNumber = Guid.NewGuid().ToString(),
                OrderDate=DateTime.Now,
                OrderGUID = ShoppingCartId,
                IsShipped = false
            };
            entities.Orders.Add(order);

            // Save changes
            entities.SaveChanges();

            //add the OrderItem for the new order
            OrderItem oi = new OrderItem()
            {
                OrderId = order.OrderId,
                OrderGUID = ShoppingCartId,
                ProductId = item.ProductId,
                ProductQuantity = item.Quantity,
                ProductPrice = item.ProductPrice
            };

            entities.OrderItems.Add(oi);
            entities.SaveChanges();
        }
        else
        {
            // If the item does exist in the cart, 
            // then add one to the quantity
            order.OrderItems.Where(p => p.ProductId == item.ProductId).FirstOrDefault().ProductQuantity++;
            entities.SaveChanges();
        }            
    }

DisplayProductsViewModel 的代码:

使用AccessorizeForLess.Data;

using System.ComponentModel.DataAnnotations;

namespace AccessorizeForLess.ViewModels
{
    public class DisplayProductsViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [DisplayFormat(DataFormatString = "{0:C}")]
        public decimal? Price { get; set; }
        public ProductImage Image { get; set; }

        public int ProductQuantity { get; set; }
    }
}

任何人都可以看到我做错了吗

修改

这是我在使用调试工具时看到的

enter image description here

修改 '这是添加了提交按钮的新视图

@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>

@{
    ViewBag.Title = "Products > Necklaces";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
    @Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))
{
    <div id="container">
        <div class="scroll">

            @foreach (var item in Model)
            {
                <div class="scroll2">
                    <div class="itemcontainer">
                        <table>
                            <tr>
                                <td id="@item.Id">
                                    <div class="DetailsLink"> &nbsp;&nbsp;&nbsp;@Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
                                    <br />
                                    <div id="@item.Id"></div>
                                    <div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
                                    <div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
                                    <div>&nbsp;</div>
                                    <div class="divQuantity">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @id = "quantity", @style = "width:50px;", @class = "formTextBox" })</div>
                                    <div class="divAddToCart">
                                        <input type="submit" value="Add To Cart" class="btn btn-default" /> @*@Html.ActionLink("Add to cart", "AddToCart", "Orders", new { id = item.Id }, new { @class = "AddToCart" })*@

                                    </div>
                                    <div style="height:15px;"></div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                    }
                    <div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
                    <br />
       </div>        
    </div>
}
@section scripts {
    <script src="~/Scripts/jQuery-jScroll.js"></script>
    <script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
    <script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
    <script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
    <script type="text/javascript">
            //$(function () {
            //    $('.scroll').jscroll({
            //        autoTrigger: true
            //    });
                $('.fancybox-thumbs').fancybox({
                    prevEffect: 'none',
                    nextEffect: 'none',

                    closeBtn: true,
                    arrows: false,
                    nextClick: false
                });

                // Document.ready -> link up remove event handler
                //$(".AddToCart").click(function () {
                //    alert('Clicked!');
                //});
            //s});
    </script>
}

AddToCart

[HttpPost]
public ActionResult AddToCart(DisplayProductDetailsViewModel model)
{
    // Retrieve the product from the database
    var productAdded = db.Products
        .Single(p => p.ProductId == model.Id);

    // Add it to the shopping cart
    var cart = ShoppingCart.GetCart(this.HttpContext);

    cart.AddToCart(productAdded);

    // Go back to the main store page for more shopping
    return RedirectToAction("Index");
}

当我在AddToCart模型中设置断点时总是为null,我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

您总是发送相同的数量,因为您始终触发仅传递查询字符串参数id的ActionLink的GET请求。表单中的数量字段永远不会作为POST表单正文提交的一部分发送。

// you are not triggering this submission: POST AddToCart
@using(Html.BeginForm("AddToCart", "Orders", FormMethod.Post))
{
    // quantity is passed on the request's body
    @Html.TextBoxFor(modelItem => item.Quantity)

    // but GET AddToCart/id is send instead
    @Html.ActionLink("Add to cart", "AddToCart", "Orders", new { id = item.Id }, new { @class = "AddToCart" })
}

如截图所示

Request URL: http://localhost:24177/Orders/AddToCart/21
Request Method: GET
Status Code: 302 Found

通知&#34;表格数据&#34;或者&#34;请求机构&#34;您的请求中缺少。

每次拨打GET AddToCart时,您都会从数据存储中查询相同的产品,并将quantity属性设置为相同的值。

你应该send this GET request as POST而不是因为:

  • 它可以被浏览器缓存,并且不会向后续请求 服务器
  • 网页抓取工具可以触发ActionLink请求

因此,在表单中添加一个提交按钮并进行POST操作。然后确保从表单中分配新数量。

[HttpPost]
public ActionResult AddToCart(FormModel model)
{
    var product = db.Products.Where(... && p => p.Id == model.ProductId);
    var quantity = model.ProductQuantity;

    cart.AddToCart(product, quantity);

    return RedirectToAction("Index");
}