将数量更改为0后,屏幕中的行不会被删除

时间:2014-03-27 23:40:38

标签: c# asp.net-mvc

在点击更新数量链接后,我可以弄清楚如何更新json或视图以删除 * 行。

我希望删除该行,并在没有它的情况下刷新视图。 这是输出和代码。

我认为我的想法是在控制器中重新执行RemoveFromCart Action Result。

我试过这个返回RedirectToAction(" RemoveFromCart",new {id = id}); 我也尝试了这个RedirectToAction(" Panier / RemoveFromCart",new {id = id});

我期待控制器分支到RemoveFromCart并执行它但似乎只是 在没有执行RemoveFromCart代码的情况下再次发送回我的视图。

我发现执行代码的唯一方法是: int itemCount = cart.RemoveFromCart(id);

有什么想法吗?

输出

Cart

Baseball glove has been remove from the cart

Payment >>
-----------

Add another article >>
----------------------

Product          Price     Quantity

Toaster          25.00       2         Update Quantity >>       Remove from Cart >>
                                       ------------------       -------------------

Baseball Glove   39.99       0         Update Quantity >>       Remove from Cart >>    *****
                                       ------------------       -------------------

Total                                  50.00 

预期产出

Cart

Baseball glove has been remove from the cart

Payment >>
-----------

Add another article >>
----------------------

Product          Price     Quantity

Toaster          25.00       2         Update Quantity >>       Remove from Cart >>
                                       ------------------       -------------------

Total                                  50.00 

PanierController.cs

        // AJAX: /ShoppingCart/RemoveFromCart/5
    [HttpPost]
    public ActionResult RemoveFromCart(int id)
    {
        object results = null;
        // Remove the item from the cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        try
        {
            // Get the name of the product to display the message
            string produitDescription = dbProduit.Paniers
                .Single(item => item.PanierId == id).Produit.Description;

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

            // Display the confirmation message
            results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(produitDescription) +
                    " a été retiré de votre panier.",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };
        }
        catch
        {
            results = new ShoppingCartRemoveViewModel
            {
                Message = "le panier a déjà été vidé.",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = 0                   
            };
        }

        return Json(results);

    [HttpPost]
    public ActionResult UpdateCartCount(int id, int cartCount)
    {
        ShoppingCartRemoveViewModel results = null;
        try 
        { 
             // Get the cart 
             var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the product to display confirmation 
             string productName = dbProduit.Paniers
                 .Single(item => item.PanierId == id).Produit.Description;

             int idProduit = dbProduit.Paniers
                 .Single(item => item.PanierId == id).Produit.ProduitId;

          /*   int nbrPanier = cart.GetCount(); */

             var prd = dbProduit.Produits.Single(produit => produit.ProduitId == idProduit);

             if (prd.Quantite - cartCount < 0)
             {
                 string msg = "Erreur la quantité dépasse celle de l'inventaire du produit, 
                             veuillez réduire la quantité ou choisir un autre produit";
                 results = new ShoppingCartRemoveViewModel
                 {
                     Message = msg,
                     CartTotal = cart.GetTotal(),
                     CartCount = cart.GetCount()
                 };
             }

             else
                 if (cartCount > 0)

                    {
                        // Update the cart count 
                        int itemCount = cart.UpdateCartCount(id, cartCount);

                        //Prepare messages
                        string msg = "La quantité de " + Server.HtmlEncode(productName) + " a été
                                      ajusté dans le panier.";
                        if (itemCount == 0) msg = Server.HtmlEncode(productName) + " a été enlevé 
                             de votre panier.";
                        //
                        // Display the confirmation message 
                        results = new ShoppingCartRemoveViewModel
                        {
                            Message = msg,
                            CartTotal = cart.GetTotal(),
                            CartCount = cart.GetCount(),
                            ItemCount = itemCount,
                            DeleteId = id
                        };
                    }
                 else
                 {

                      /* RedirectToAction("Panier/RemoveFromCart", new { id = id });  */ 
                      /* return RedirectToAction ("Panier/RemoveFromCart", new { id = id }); */

                     int itemCount = cart.RemoveFromCart(id);
                     results = new ShoppingCartRemoveViewModel
                     {
                         Message = Server.HtmlEncode(productName) + " a été retiré de votre 
                                       panier.",
                         CartTotal = cart.GetTotal(),
                         CartCount = cart.GetCount()
                     };

                 }
        }
        catch 
        {
            results = new ShoppingCartRemoveViewModel
            {
                Message = "Une erreur est survenue ou données en entrée erronnées...",
                CartTotal = -1,
                CartCount = -1,
                ItemCount = -1,
                DeleteId = id
            };
        }
        return Json(results);
    }

ShoppingCart.cs

    public int GetCount()
    {
        // Get the count of each item in the cart and sum them up
        int? count = (from cartItems in db.Paniers
                      where cartItems.CartId == ShoppingCartId
                      select (int?)cartItems.Quantite).Sum();
        // Return 0 if all entries are null
        return count ?? 0;
    }
    public decimal GetTotal()
    {
        // Multiply album price by count of that album to get 
        // the current price for each of those albums in the cart
        // sum all album price totals to get the cart total
        decimal? total = (from cartItems in db.Paniers
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems .Quantite *
                          cartItems.Produit.Prix).Sum();

        return total ?? decimal.Zero;
    }

    public int UpdateCartCount(int id, int cartCount)
    {
        // Get the cart 
        var cartItem = db.Paniers.Single(
            cart => cart.CartId == ShoppingCartId
            && cart.PanierId == id);

        int itemCount = 0;

        if (cartItem != null)
        {
            if (cartCount > 0)
            {

                cartItem.Quantite = cartCount;
                itemCount = cartItem.Quantite;
            }
            else
            {
                db.Paniers.Remove(cartItem);
            }
            // Save changes 
            db.SaveChanges();
        }
        return itemCount;
    }     

Index.cshtml

 @model Tp1WebStore3.ViewModels.ShoppingCartViewModel

 @{
     ViewBag.Title = "Shopping Cart";
 }

 @using (Html.BeginForm())
 { 
 <h3>
     <em>Visualisation </em> du panier:

     @if (TempData["err_message"] != null)
     {
         @TempData["err_message"]
     }

 </h3>

 <script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>

 <script type="text/javascript">
     $(function () {
         $('.RemoveLink').click(function () {
             $.ajax({
                 url: '@Url.Action("RemoveFromCart","Panier")',
                 data: { id: $(this).data('id') },
                 type: 'POST',
                 cache: false,
                 success: function (result) {
                     $('#row-' + result.DeleteId).remove();
                     $('#row-' + result.DeleteId).fadeOut('slow');
                     $('#cart-status').text('Panier (' + result.CartCount + ')');
                     $('#update-message').text(result.Message);
                     $('#cart-total').text(result.CartTotal);
                     $.get('@Url.Action("CartSummary", "Panier")');
                     $('#content').html(result);
                 },
                 error: function(XMLHttpRequest, textStatus, errorThrown) {
                      alert("Status: " + textStatus); alert("Error: " + errorThrown);
                  }
             });
             return false;
         });
     });

     $(function () {
         $(".RefreshQuantity").click(function () {
             // Get the id from the link 
             var recordToUpdate = $(this).attr("data-id");

             var countToUpdate = 0;
             if ($("#" + $(this).attr("id")).val() !== '') {
                 countToUpdate = $("#" + $(this).attr("id")).val();
             }
             if (recordToUpdate != '') {        
                 // Perform the ajax post 
                 $.post("/Panier/UpdateCartCount", { "id": recordToUpdate, "cartCount": 
                          countToUpdate },
                 function (data) {
                    // Successful requests get here 
                    // Update the page elements                        
                    if (data.ItemCount == 0) {
                        $('#row-' + data. DeleteId).fadeOut('slow');
                    }
                    $('#update-message').text(htmlDecode(data.Message));
                    $('#cart-total').text(data.CartTotal);
                    $('#cart-status').text('Cart (' + data.CartCount + ')');
                    //Only process the callback data when no server error occurs
                    if (data.ItemCount != -1) {
                        $('#cart-total').text(data.CartTotal);
                        $('#cart-status').text('Panier (' + data.CartCount + ')');
                    }
                 }
             );
           }
        });
     });

     $(function () {
         if (typeof String.prototype.trim !== 'function') {
             String.prototype.trim = function () {
                 return this.replace(/^\s+|\s+$/g, '');
             }
         }
     });

     function clearUpdateMessage() {
         // Reset update-message area
         $('#update-message').text('');
     }

     function htmlDecode(value) {
         if (value) {
             return $('<div />').html(value).text();
         }
         else {
             return '';
         }
     }
 </script>



 <div>
@for (int i = 0; i < Model.CartItems.Count; i++)
{ 
    <p>
        @Html.ValidationMessageFor(model => model.CartItems[i].Quantite)
    </p> 
}
 </div>

 <div id="update-message" style="color:red;" >

 </div>

 <div id="content">
     @if (Model.CartTotal != 0)
     {
         <p class="button">
             @Html.ActionLink("Paiement >>", "AddressAndPayment", "Checkout")
         </p>
         <p class="NouvelAjout">
             @Html.ActionLink("Ajouter un autre article >>", "Magasin", "Home")
         </p>
     }

<table>
    <tr>
        <th>
            Produit
        </th>
        <th>
            Prix (unitaire)
        </th>
        <th>
            Quantite
        </th>
        <th></th>
    </tr>

    @{int ix = 0;}

    @foreach (var item in Model.CartItems)
    {
        <tr id="row-@item.ProduitId">
            <td>
                @Html.ActionLink(item.Produit.Description, "Details", "Produit", new { id = 
                       item.ProduitId }, null)
            </td>
            <td>
                @item.Produit.Prix
            </td>
            <td>
                @Html.TextBoxFor(model => model.CartItems[ix].Quantite, 
                    new  {style = "width:30px; text-align:right;",
                    onkeyup = "clearUpdateMessage();",
                    onchange = "clearUpdateMessage();"
                    }) 
            </td>
            <td style="width: 200px">
                <a href="#" class="RefreshQuantity" data-id="@item.PanierId" 
                   id="CartItems_@(ix)__Quantite"> Mettre à jour la quantité >> <a />
            </td>

            <td style ="width: 200px">
                <a href="#" class="RemoveLink" data-id="@item.PanierId"> Enlever du panier >> 
                </a>
            </td>
        </tr>
        ix++;
    }

    <tr>
        <td>
            Total
        </td>
        <td></td>
        <td></td>
        <td id="cart-total">
            @Model.CartTotal
        </td>
    </tr>
</table>
 </div>

 }

0 个答案:

没有答案