asp.net-mvc如何从已更新为数量字段的视图返回值?

标签: Asp.net-MVC Razor
发布时间: 2016/10/9 6:13:53
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试图了解如何从视图获取最新的价值。 第一次我来在屏幕中的数量是 1。 我更新的数量为 2。

当我在表演 int nbrCart = cart.GetCount(); 仍然有 1。我猜这是因为车没有更新,仍然包含初始值为 1。

问题是怎样才能从用户从索引中添加新值?

@Html.TextBoxFor(model => model.CartItems[ix].Quantity

Index.cshtml

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

CartController.cs

       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 = dbProduct.Carts
                 .Single(item => item.CartId == id).Product.Description;

             int nbrCart = cart.GetCount();   <=== the number is 1  and it should be 2
                                                   since I update the quantity to 2

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

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>

 }

PanierController.cs

         [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 nbrPanier = cart.GetCount();

              // 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
             };
        }
        catch 
        {
            results = new ShoppingCartRemoveViewModel
            {
                Message = "Error occurred or invalid input...",
                CartTotal = -1,
                CartCount = -1,
                ItemCount = -1,
                DeleteId = id
            };
        }
        return Json(results);
    }

解决方法 1:

像这样一些东西。

通过 Jquery async call 你可以做如下︰

<script type="text/javascript">
    $(document).ready(function () {
         $('#Quantity').blur(function () { //Quantity Textbox Blur event or update button click event you can use
              $.post('@Url.Action("UpdateCartCount")', { 'id': 'User Id Here', 'cartCount': this.value  }, function (data) { // Post the updated value to your controller - Action Result
                  $('#DivQuantity').html(data); // Refreshing Quantity 
              });
         });
    });
</script>
赞助商