2016-12-02 75 views
0

我的团队和我一直在为我们的网站努力寻找答案,我们终于踏出了一步,向社区寻求帮助!ASP.NET MVC - 从购物车中删除

的目标是尝试并链接我们网站的按钮,“从购物车中删除”,并设置数据库恢复到0,以及刷新页面,并显示递减发生。

,购物车视图的javascript似乎并没有工作,但我不知道这是否是最终的问题。我们已经遵循了很多指南,例如MVC音乐商店和ASP.NET文档。

Index.cshtml:

script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(function() { 
     // Document.ready -> link up remove event handler 
     $(".RemoveLink").click(function() { 
      // Get the id from the link 
      var recordToDelete = $(this).attr("data-id"); 

      if (recordToDelete != '') { 
       // Perform the ajax post 
       $.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete }, 
        function (data) { 
         // Successful requests get here 
         // Update the page elements 
         if (data.ItemCount == 0) { 
          $('#row-' + data.DeleteId).fadeOut('slow'); 
         } else { 
          $('#item-count-' + data.DeleteId).text(data.ItemCount); 
         } 

         $('#cart-total').text(data.CartTotal); 
         $('#update-message').text(data.Message); 
         $('#cart-status').text('Cart (' + data.CartCount + ')'); 
        }); 
      } 
     }); 

    }); 


    function handleUpdate() { 
     // Load and deserialize the returned JSON data 
     var json = context.get_data(); 
     var data = Sys.Serialization.JavaScriptSerializer.deserialize(json); 

     // Update the page elements 
     if (data.ItemCount == 0) { 
      $('#row-' + data.DeleteId).fadeOut('slow'); 
     } else { 
      $('#item-count-' + data.DeleteId).text(data.ItemCount); 
     } 

     $('#cart-total').text(data.CartTotal); 
     $('#update-message').text(data.Message); 
     $('#cart-status').text('Cart (' + data.CartCount + ')'); 
    } 
</script> 

<h3> 
    <em>Review</em> your cart: 
</h3> 
<div id="update-message"> 
</div> 

<div style="height:600px; overflow:auto; padding-top: 50px; margin-left: 200px; width: 1050px; "> 
    <table id="cart-summary" border="1" frame="void" rules="rows" style="width:100%;margin-left:auto; margin-right: auto;"> 
     <tr class="data-table"> 
      <th colspan="1"> 
       Item(s) 
      </th> 
      <th colspan="1" style="text-align:center;"> 
       Price 
      </th> 
      <th colspan="1" style="text-align:center;"> 
       Quantity 
      </th> 
      <th colspan="1" style="text-align:center;"> 
       Total 
      </th> 
      <th></th> 
     </tr> 


     @foreach (var item in Model.CartItem) 
     { 
      <tr> 
       <td style="margin:auto;width:500px;"> 
        <div style="float:left;"> 
         <a [email protected](String.Format("~/Books/Details/{0}", item.Book.id))> 
          <img class="img-responsive" src="@Url.Content(String.Format("~/Content/img/books/{0}.jpg",item.Book.ISBN))" style="width: 100px; height: 150px;" /> 

         </a> 
        </div> 

        <div style="margin-top:37px;"> 
         <a [email protected](String.Format("~/Books/Details/{0}", item.Book.id))> 
          <span>@Html.DisplayFor(modelItem => item.Book.Title)</span><br /> 
         </a> 
         <span style="text-align:left;">@Html.DisplayFor(modelItem => item.Book.Author)</span><br /><br /> 
         <span style="text-align:left">ISBN: @Html.DisplayFor(modelItem => item.Book.ISBN)</span> 
        </div> 

       </td> 
       <td> 
        <p style="text-align:center;">@item.Book.PriceNew</p> 
       </td> 

       <td> 
        <p style="text-align:center;">@item.Quantity</p> 
        <a href="#" class="RemoveLink" data-id="@item.RecordId">Remove from cart</a> 
        <!--data-url='Url.Content("~/ShoppingCart/RemoveFromCart")'> 
         Remove from cart 
        </a>--> 
       </td> 
       <td> 
        <p>@Model.CartTotal</p> 
       </td> 
      </tr> 
     } 
     <tr> 
      <td></td> 
      <td> 
       <p style="padding-top:15px;"></p> 
       <br /> 
       <button type="button"> 
        @Html.ActionLink("Back to List", "../Books/Index") 
       </button> 
      </td> 
      <td></td> 
      <td id="cart-total"> 
       <p style="padding-top: 10px;font-weight:bold;color:rgb(179,0,0);font-size:18px;">Subtotal: @Model.CartTotal</p> 
       <button type="button"> 
        @Html.ActionLink("Checkout!", "AddressAndPayment", "Checkout") 
       </button> 
      </td> 
     </tr> 

    </table> 
</div> 

下一组的代码是C#代码。 Cart.cs:

public int RemoveFromCart(int id) 
     { 
      var cartItem = bookDb.Carts.Single(
       c => (c.CartId == ShoppingCartId) 
       && c.RecordId == id); 

      int itemCount = 0; 

      if (cartItem != null) 
      { 
       if (cartItem.Quantity > 1) 
       { 
        cartItem.Quantity--; 
        itemCount = cartItem.Quantity; 
       } 
       else 
       { 
        bookDb.Carts.Remove(cartItem); 
       } 
       bookDb.SaveChanges(); 
      } 

      return itemCount; 
     } 

最后完成MVC组用于彼此相关的代码。我们也相信这里可能有一个错误。再次,我们只是没有足够的经验知道。

ShoppingCartController.cs:

// GET: ShoppingCart 
     public ActionResult Index() 
     { 
      var cart = ShoppingCart.GetCart(this.HttpContext); 

      // Set up our View Model 
      var viewModel = new ShoppingCartViewModel 
      { 
       CartItem = cart.GetCartItems(), 
       CartTotal = cart.GetTotal() 
      }; 
      return View(viewModel); 
     } 

     // GET: Book/Details/5 
     // Button that allows you to add to the cart you will be redirected to the Shopping cart index page 
     public ActionResult AddToCart(string id) 
     { 
      var addedBook = bookdb.Books.Single(book => book.ISBN == id); 

      var cart = ShoppingCart.GetCart(this.HttpContext); 

      cart.AddToCart(addedBook); 

      bookdb.SaveChanges(); 

      return RedirectToAction("Index"); 
     } 

     // this is attached to the remove to cart button in the shopping cart index page, the index page will then reload 
     [HttpPost] 
     public ActionResult RemoveFromCart(int id) 
     { 
      // Retrieve the current user's shopping cart 
      var cart = ShoppingCart.GetCart(this.HttpContext); 

      // Get the name of the book to display confirmation 
      string bookName = bookdb.Carts.Single(book => book.RecordId == id).Book.Title; 

      // Remove from cart 
      int itemCount = cart.RemoveFromCart(id); 

      // Display confirmation message 
      var results = new ShoppingCartRemoveViewModel 
      { 
       Message = Server.HtmlEncode(bookName) + " has been removed from the shopping cart", 
       CartTotal = cart.GetTotal(), 
       CartCount = cart.GetCount(), 
       ItemCount = itemCount, 
       DeleteId = id 
      }; 
      //return view(); 
      return Json(results); 
     } 

感谢一大堆!

+0

嗨!你可以创建一个演示[这里](https://dotnetfiddle.net/)? – karritos

+0

是否按照期望的服务器端删除了该项目,即,当您点击此API端点时,是从数据库中删除的项目? –

+0

这是,我终于明白了。如果您注意到第一个代码块,它会显示两个脚本。第二个格式不正确,这就是jQuery被“忽略”的原因。然后,我必须添加以下代码行:@ Ajax.ActionLink(“Remove”,“Index”,“ShoppingCart”,new {LoadingElementId = item.RecordId},new AjaxOptions {OnSuccess =“handleUpdate”},new { class =“RemoveLink”,@ data_id = @ item.RecordId})'以便网站识别按钮/链接将执行jQuery函数。我回答,以防万一有问题!似乎是一个常见问题。 –

回答

3

Index.cshtml

<script> 


$(document).on('click', '.del-CartDetail', function() {  

var id = $(this).data("id");   

$("#hdnCartDetailId").val(id);  

$("#modal-del-cartdetail").modal({    

backdrop: 'static',  
keyboard: false,   
show: true  
    }); 

}); 


$("#btnModalSubmit").click(function() {   
    var buttonText = $("#btnModalSubmit").html(); 
    $("#btnModalSubmit").attr('disabled', '').html('<i class="fa fa-spinner fa-spin"></i>&nbsp; ' + buttonText); 


var id = $("#hdnCartDetailId").val(); 


$.ajax({ 
      url: '/CartDetail/DeleteCartDetail', 
      type: "POST", 
      dataType: "json", 
      contentType: 'application/json; charset=utf-8', 
      data: JSON.stringify({ Id: id }), 
      success: function (result) { 
       debugger; 
       if (result.success) { 
        $('#modal-del-cartdetail .close').click(); 
        //Page redirect after delete record 
        window.location.reload(); 
        $('#modal-del-cartdetail').show(); 
        INTAPP.Util.Notification(true, "Selected Cart(s) have been successfully deleted."); 
       } else { 
        INTAPP.Util.HandleLogout(data.message); 
        INTAPP.Util.Notification(false, "Some error occured while deleting selected Cart."); 
       } 

       $("#btnModalSubmit").attr('disabled', null).html('Submit'); 
      }, 
      error: function (xhr, status, error) { 
       INTAPP.Util.Notification(false, error); 
       $("#btnModalSubmit").attr('disabled', null).html('Submit'); 
      } 
     }); 
    });  
</script> 


@Html.Partial("ConfirmModal", new ModalViewModel 
    { 
     Id = "modal-del-cartdetail", 
     IsAlertModel = false, 
     Title = "Delete Product", 
     Message = "Are you sure you want to delete the cart detail?", 
     HiddenElementId = "hdnCartDetailId" 
    }) 
+0

我建议注释你的代码。这是作者问题的最终解决方案吗?代码不短,可能会解释它会有帮助。 – YakovL