0

I will like to request your help to debug my Jquery which seems not to pick-up my new count for the quantity.

I am in my application and I added a product, I changed the quantity of the item from 1 to 3. I clicked the refresh button. I was expecting the total will be changed (total X 3) instead of (total X 1)

I think the problem is coming from the cartCount variable. this variable doesn't seems to get the new count of the @html.TextBoxFor field from the view.

I got an error with the javascript RefreshQuantity :

In Chrome Pf12, in the header tab

I can see

header tab

 id:320
 cartCount:0

 The id 320 is the corresponding id in the Panier table.

Preview tab

 {Message: Error occured or invalid input...,CartTotal:-1, ItemCount:-1, DeleteId:210}
 CartCount: -1
 CartTotal: -1
 DeleteId: 320
 ItemCount: -1
 Message: "Error occurred or invalid input..."

Response Tab

 {"Message":"Error occurred or invalid 
          input...","CartTotal":-1,"CartCount":-1,"ItemCount":-1,"DeleteId":320}

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('Cart (' + 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('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].Quantite)
     </p> 
}
 </div>

 <div id="update-message">

 </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>
                     <a href="#" class="RefreshQuantity" data-id="@item.PanierId"
                        id="CartItems_@(ix)__Count">Refresh quantity</a>&nbsp;|&nbsp;  />a
                 </td>
                 <td>
                     <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>

 }

Do we have anyway to debug the javascript from Visual Studio? I saw a post which is stating it was a problem with Visual studio ref.: Visual Studio 2013 can't debug javascript in cshtml

ShoppingCart.cs

        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)    <===  cartCount is always 0  it should contains the new value
                                        added from the view.
            {

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

I need to know how to extract the new value added by the user in the screen from the view field

               @Html.TextBoxFor(model => model.CartItems[ix].Quantite, 
                    new  {style = "width:30px; text-align:right;",
                    onkeyup = "clearUpdateMessage();",
                    onchange = "clearUpdateMessage();"
                    }) 
Community
  • 1
  • 1
user3127986
  • 388
  • 1
  • 10
  • 33

2 Answers2

1

Change to textbox:

@Html.TextBoxFor(model => model.CartItems[ix].Quantite, 
                    new  {style = "width:30px; text-align:right;",
                    onkeyup = "clearUpdateMessage();",
                    onchange = "clearUpdateMessage();",
                    @class="new-count"
                    })

Change to script:

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

                  var countToUpdate = $(this)
                                       .closest('tr')
                                       .find('.new-count').val();
Ivan Doroshenko
  • 944
  • 7
  • 13
0

The error was on the Index.cshtml with the var id="CartItems_@(ix)__Count"

old view

             <td>
                 <a href="#" class="RefreshQuantity" data-id="@item.PanierId"
                    id="CartItems_@(ix)__Count">Refresh quantity</a>&nbsp;|&nbsp;  />a
             </td>

Modified

             <td>
                 <a href="#" class="RefreshQuantity" data-id="@item.PanierId"
                    id="CartItems_@(ix)__Quantite">Refresh quantity</a>&nbsp;|&nbsp;  />a
             </td>
user3127986
  • 388
  • 1
  • 10
  • 33