【问题标题】:asp.net ajax not sending dataasp.net ajax不发送数据
【发布时间】:2018-04-13 02:49:53
【问题描述】:

我的 AJAX 没有向我的 http post 控制器发送数据。

我的控制器:

[Route("api/sendingData")]
public class TestController : ApiController
{
    [HttpPost]
    public string Post([FromBody] int propertyID)
    {
        return string.Format("Test");
    }
}

我的 AJAX:

$.ajax(
    {
        url: "api/sendingData",
        type: "POST",
        dataType: 'json',
        data: {
            'propertyID': '1'
        },
        success: function (result) {
            console.debug(result);
            alert(result);
        },
        error: function (xhr, status, p3, p4) {
            console.debug(xhr);
            var err = "Error " + " " + status + " " + p3;
            if (xhr.responseText && xhr.responseText[0] == "{")
                err = JSON.parse(xhr.responseText).message;
            alert(err);
        }
    });

我正在尝试发送propertyID=1。但是,当我调试控制器时,它显示propertyID=0

有谁知道怎么回事?

【问题讨论】:

  • 请测试一下:data: { propertyID: JSON.stringify('1')}
  • 谢谢。但还是同样的问题
  • 去掉单引号试试看:data: {propertyID: 1 },
  • 解决方案:数据:{“”:1}。我不知道为什么
  • 另外,[FromBody] 可能是问题所在。如果您将其删除或改用 [FromUri] 会怎样?

标签: jquery asp.net ajax asp.net-web-api


【解决方案1】:

可能看起来很奇怪,但你只发送一个值,而不是模型,所以 stringify 是 JSON.stringify(value)

var propertyID = 1;
$.ajax({
    url: "api/sendingData",
    contentType: 'application/json',
    type: 'POST',
    data: JSON.stringify(propertyID),
    success: function (result) {
        console.debug(result);
        alert(result);
    },
    error: function (xhr, status, p3, p4) {
        console.debug(xhr);
        var err = "Error " + " " + status + " " + p3;
        if (xhr.responseText && xhr.responseText[0] == "{")
            err = JSON.parse(xhr.responseText).message;
        alert(err);
    }
});

我还删除了 dataType json 因为您的操作方法不是返回 json 而是一个字符串。现在我取得了成功。

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 2020-09-19
    • 2017-01-12
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2016-03-09
    相关资源
    最近更新 更多