将数量更改为0后,视图未正确刷新 [英] View is not refreshing correctly after I changed the quantity to 0

查看:61
本文介绍了将数量更改为0后,视图未正确刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将物品的数量更改为0后,我的屏幕无法完全刷新。



现在输出



I have trouble to have my screen perfectly refresh after I changed the quantity to 0 for an item.

Output now

Cart

Baseball Bat has been remove from the cart

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

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

Product          Price     Quantity

Oil Castrol      25.00       2         Update Quantity >>       Remove from Cart >>
                                       ------------------       -------------------

Baseball Bat     79.99       0         Update Quantity >>       Remove from Cart >>    
                                       ------------------       -------------------

Total                                  50.00 







预期产量






Expected output

Cart

Baseball Bat has been remove from the cart

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

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

Product          Price     Quantity

Oil Castrol      25.00       2         Update Quantity >>       Remove from Cart >>
                                       ------------------       -------------------

Total                                  50.00 







index.cshtml






index.cshtml

 @model WebStore.ViewModels.ShoppingCartViewModel

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

 @using (Html.BeginForm())
 { 
 <h3>
     Cart  :

     @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","Cart")',
                 data: { id: $(this).data('id') },
                 type: 'POST',
                 cache: false,
                 success: function (result) {
                     $('#row-' + result.DeleteId).remove();
                     $('#row-' + result.DeleteId).fadeOut('slow');
                     $('#cart-status').text('Cart (' + result.CartCount + ')');
                     $('#update-message').text(result.Message);
                     $('#cart-total').text(result.CartTotal);
                     $.get('@Url.Action("CartSummary", "Cart")');
                     $('#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("/Cart/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('Cart (' + 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].Quantity)
    </p> 
}
 </div>

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

 </div>

 <div id="content">
     @if (Model.CartTotal != 0)
     {
         <p class="button">
             @Html.ActionLink("Payment >>", "AddressAndPayment", "Checkout")
         </p>
         <p class="AddNewItem">
             @Html.ActionLink("Add another item >>", "Store", "Home")
         </p>
     }

<table>
    <tr>
        <th>
            Product
        </th>
        <th>
            Price
        </th>
        <th>
            Quantity
        </th>
        <th></th>
    </tr>

    @{int ix = 0;}

    @foreach (var item in Model.CartItems)
    {
        <tr id="row-@item.ProductId">
            <td>
                @Html.ActionLink(item.Product.Description, "Details", "Product", new { id = 
                       item.ProductId }, null)
            </td>
            <td>
                @item.Product.Price
            </td>
            <td>
                @Html.TextBoxFor(model => model.CartItems[ix].Quantity, 
                    new  {style = "width:30px; text-align:right;",
                    onkeyup = "clearUpdateMessage();",
                    onchange = "clearUpdateMessage();"
                    }) 
            </td>
            <td style="width: 200px">
                <a href="#" class="RefreshQuantity" data-id="@item.CartId" 
                   id="CartItems_@(ix)__Quantity> Update Quantity >> <a />
            </td>

            <td style ="width: 200px">
                <a href="#" class="RemoveLink" data-id="@item.CartId"> Remove from Cart >> 
                </a>
            </td>
        </tr>
        ix++;
    }

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





CartControler.cs





CartControler.cs

         {

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

             int itemCount = cart.RemoveFromCart(id);
             results = new ShoppingCartRemoveViewModel
             {
                 Message = Server.HtmlEncode(productName) + " has been removed from your
                               Cart.",
                 CartTotal = cart.GetTotal(),
                 CartCount = cart.GetCount()
             };

         }
}
catch
{
    results = new ShoppingCartRemoveViewModel
    {
        Message = "error with the data...",
        CartTotal = -1,
        CartCount = -1,
        ItemCount = -1,
        DeleteId = id
    };
}
return Json(results);





ShoppingCart.cs





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

推荐答案

(function(){
(function () {


' 。RemoveLink')。click(function(){
('.RemoveLink').click(function () {


.ajax({
url:' @ Url.Action(RemoveFromCart,Cart)'
数据:{id:
.ajax({ url: '@Url.Action("RemoveFromCart","Cart")', data: { id:


这篇关于将数量更改为0后,视图未正确刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆