【问题标题】:Javascript value not beeing extracted from the @html.TextBoxFor in a view未从视图中的 @html.TextBoxFor 提取 Javascript 值
【发布时间】:2014-05-05 13:45:44
【问题描述】:

我想请求您的帮助来调试我的 Jquery,它似乎无法获取我的新数量。

我在我的应用程序中添加了一个产品, 我将项目的数量从 1 更改为 3。我单击了刷新按钮。 我期待总数会改变(total X 3)而不是(total X 1)

我认为问题出在 cartCount 变量上。这个变量似乎没有 从视图中获取 @html.TextBoxFor 字段的新计数。

javascript RefreshQuantity 出现错误:

在 Chrome Pf12 中,在标题选项卡中

我可以看到

标题标签

 id:320
 cartCount:0

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

预览标签

 {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..."

响应选项卡

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

索引.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>

 }

我们是否需要从 Visual Studio 调试 javascript?我看到一个帖子说这是 Visual Studio 参考的问题: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;
    }

我需要知道如何从视图字段中提取用户在屏幕中添加的新值

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

【问题讨论】:

    标签: javascript jquery c#-4.0 visual-studio-2012


    【解决方案1】:

    更改为文本框:

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

    更改为脚本:

    $(".RefreshQuantity").click(function () {
                      // Get the id from the link 
                      var recordToUpdate = $(this).attr("data-id");
    
                      var countToUpdate = $(this)
                                           .closest('tr')
                                           .find('.new-count').val();
    

    【讨论】:

      【解决方案2】:

      错误出现在 Index.cshtml 上,var id="CartItems_@(ix)__Count"

      旧视图

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

      修改

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        • 2014-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多