【问题标题】:How to pass data/value to controller by using query string in AJAX如何使用 AJAX 中的查询字符串将数据/值传递给控制器
【发布时间】:2019-10-14 23:55:39
【问题描述】:

“pid”值工作正常,“qty”值在控制器上显示为“0”。

我 100% 确定问题出在查询字符串上。

这里是 ajax 和 jquery 代码:

$(".cartquantity").change(function () {
    var tblrow = $(this).parents(".datarow");
    var amtcell = $("#amtcell").text();
    var pid = $(this).data("pid");
    var qty = $(this).val();
    var price = $("#prc").text();
    $.ajax(
        {
            url: "/cart/UpdateQuantity?pid=" + pid + "&qty" + qty //here problem occurs
        }
    ).done(function (result) {
        if (qty < 1)
            tblrow.remove();
        else
            amtcell.text(price * qty);
        $("#cartitems").text(result.Items)
    });
});

Controller Code:

int pid = Convert.ToInt32(Request.QueryString["pid"]);
int qty = Convert.ToInt32(Request.QueryString["qty"]); //showing "0"

请告诉我通过查询字符串传递值的正确语法是什么。因为 qty 变量显示正确的值,但是当数据通过查询字符串时,它变为 0。

【问题讨论】:

  • 查询字符串中的qty 缺少=,应该是"&amp;qty=" + qty
  • 请添加一次` url: "/cart/UpdateQuantity?pid=" + pid + "&qty=" + qty`

标签: javascript jquery ajax asp.net-mvc


【解决方案1】:

请试试这个

$(".cartquantity").change(function () {
    var tblrow = $(this).parents(".datarow");
    var amtcell = $("#amtcell").text();
    var pid = $(this).data("pid");
    var qty = $(this).val();
    var price = $("#prc").text();
    $.ajax(
        {
            url: "/cart/UpdateQuantity?pid=" + pid + "&qty=" + qty //here problem occurs
        }
    ).done(function (result) {
        if (qty < 1)
            tblrow.remove();
        else
            amtcell.text(price * qty);
        $("#cartitems").text(result.Items)
    });
});
Controller Code:
int pid = Convert.ToInt32(Request.QueryString["pid"]);
int qty = Convert.ToInt32(Request.QueryString["qty"]); //showing "0"

【讨论】:

  • 谢谢吉山
  • 欢迎您,兄弟 :) 很高兴为您提供帮助。
【解决方案2】:

有一个错误,你在url中发送数据时没有在qty之前使用=

$(".cartquantity").change(function () {
    var tblrow = $(this).parents(".datarow");
    var amtcell = $("#amtcell").text();
    var pid = $(this).data("pid");
    var qty = $(this).val();
    var price = $("#prc").text();
    $.ajax(
        {
            url: "/cart/UpdateQuantity?pid=" + pid + "&qty=" + qty // problem Solved
        }
    ).done(function (result) {
        if (qty < 1)
            tblrow.remove();
        else
            amtcell.text(price * qty);
        $("#cartitems").text(result.Items)
    });
});

Controller Code:

int pid = Convert.ToInt32(Request.QueryString["pid"]);
int qty = Convert.ToInt32(Request.QueryString["qty"]); //showing "0"

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多