【问题标题】:Text change event for textbox not updating assigned value文本框的文本更改事件未更新分配的值
【发布时间】:2015-06-22 14:42:21
【问题描述】:

我正在构建一个购物门户,我需要在其中接受产品数量并将其传递给名为 order 的操作

如上图所示,我为每个产品添加了一个接受数量的文本框,然后我使用以下代码构建了一个操作链接

@Html.ActionLink("Order Now", "OrderNow", "ShoppingCart", new { id = item.prod_id, qty = @quantity }, new { style = "color: white;" })

为了获取数量,我添加了新的 int 数量属性来查看,如

int quantity = 1;

但是当用户更改数量文本框中的文本时如何更新这个数量变量。

下面是我的查看代码:

  @Html.TextBox("qty","", new { id=@item.prod_name, placeholder="Qty", style="width:20px; height:15px; font-size:small;" })
                <script type="text/javascript">
                    $('#@item.prod_name').change(function () {

                        }
                    });
                </script>
                @Html.ActionLink("Order Now", "OrderNow", "ShoppingCart", new { id = item.prod_id, qty = @quantity }, new { style = "color: white;" })

这是我的控制器操作方法

  public ActionResult OrderNow(int id, int qty)
    {
        if (Session["cart"] == null)
        {
            List<Item> cart = new List<Item>();
            cart.Add(new Item(p.FirstOrDefault(), qty));
            Session["cart"] = cart;
            return RedirectToAction("ViewCart", new { ids = p.FirstOrDefault().prod_sub_cat_id });
        }
        else
        {
            List<Item> cart = (List<Item>)Session["cart"];

                cart[index].quantity = qty;
            Session["cart"] = cart;
            return RedirectToAction("ViewCart", new { ids = p.FirstOrDefault().prod_sub_cat_id });
        }

    }

【问题讨论】:

  • 您需要使用 javascript/jquery 更新它,或者使用表单发布值。
  • 在文本框的 onchange 事件中使用隐藏字段使用 javascript/jquery 更新其值
  • @StephenMuecke 查看我的视图代码并建议我需要更改的地方
  • 你的控制器是什么?它是如何发布的? GET 中的数量是如何分配的?您想要实时更新还是仅针对POST ..
  • @gerdi 查看我的编辑.. 添加了我的操作方法.. 我需要更新路线以接受两个参数

标签: c# asp.net-mvc views


【解决方案1】:

你并不真正想要一个指向 GET 方法的链接。您的修改数据(并且不希望将其添加到浏览器历史记录中),因此您应该发布数据。对于每个产品,添加一个表单元素,其中包含一个数量文本框和一个“立即订购”操作的提交按钮(如果需要,可以将其设置为看起来像一个链接)

@using (Html.BeginForm("OrderNow", "ShoppingCart", new { id = item.prod_id })
{
  <input type="text" class="???" name="qty" placeholder="Qty" />
  <input type="submit" value="Order Now" class="???" />
}

旁注:

  1. 添加类名并使用 css 而不是包括内联样式 作为style="width:20px; height:15px; font-size:small;"
  2. 您也可以使用@Html.TextBox("qty", new { id = "", @class="???", placeholder = "Qty"),但请注意id = "" 删除 id 属性以防止由于重复导致的无效 html

【讨论】:

  • 让我试试这个。我需要更改我的控制器签名吗?
  • 只是另一个注释(尽管它不再相关),但永远不会为每个项目生成脚本。正确的方法是在文本框中添加一个类名(不是id)并使用一个脚本,例如$('.qty').change(function() { var link = $(this).next('a'); ...});(或类似的相对选择器来获取相关链接)
  • 我的错!从现在开始,我会照顾好这个的!
猜你喜欢
  • 1970-01-01
  • 2014-01-26
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
相关资源
最近更新 更多