elliott.david 2017-10-31 20:13 采纳率: 25%
浏览 39

asp.net ajax不发送数据

My AJAX is not sending data to my http post controller.

My controller:

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

My 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);
        }
    });

I'm trying to send the propertyID=1. However, when I debug my controller, it shows propertyID=0.

Does anyone know what is wrong?

  • 写回答

1条回答 默认 最新

  • 乱世@小熊 2017-10-31 20:39
    关注

    Might look weird but you're only sending one value, not a model, so the stringify is 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);
        }
    });
    

    Also I have removed dataType json because your action method is not returning json but a string. Now I'm getting success.

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站