【问题标题】:Setting a value using jQuery to post JSON to an ASP.Net Web API 2 service使用 jQuery 设置值以将 JSON 发布到 ASP.Net Web API 2 服务
【发布时间】:2014-05-07 16:56:59
【问题描述】:

我有一个看似简单的 jQuery ajax 函数将整数数组发布到 Web 服务:

$(document).ready(function() {
    $("#testButton").click(function() {
        $.ajax({
            type: "POST",
            url: "api/setactivedemodatasetids/",
            data: [1, 2, 8, 9],
            success: function() {},
            dataType: "application/json"
        });
    });
});

还有一个简单的 ASP.Net Web API 2 控制器来接收发布的数据:

[Route("api/setactivedemodatasetids/")]
[AcceptVerbs("POST")]
public void SetActiveDemoDataSetIds(int[] ids)
{
    var db = new DataClassesDataContext();
    // Do stuff
    db.SubmitChanges();
}

当我在控制器中设置断点时,参数ids的值为

{int[0]}

为什么?为什么不是由 1、2、8、9 四个整数组成的数组呢?

【问题讨论】:

    标签: jquery asp.net ajax json asp.net-web-api2


    【解决方案1】:

    设置dataType: "json" 设置contentType: "application/json; charset=utf-8" 和数据:JSON.stringify([1, 2, 8, 9] )

    https://api.jquery.com/jQuery.ajax/

    我认为这段代码会解决你的问题

    $("#testButton").click(function () {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            url: "api/setactivedemodatasetids/",
                            data: JSON.stringify([1, 2, 8, 9]),
                            success: function () { },
                            error: function (xhr, ajaxOptions, thrownError) {
                                alert(xhr.status);
                                //alert(xhr.responseText);
                                alert(thrownError);
                            }
    
                        });
                    });
    

    【讨论】:

    • 这改变了我在控制器断点处看到的ids 的值从{int[0]}null,而不是我希望的整数数组。不过谢谢你的建议。
    • 宾果游戏!我知道了,我会编辑你的答案并接受它。数据应该是JSON.stringify([1, 2, 8, 9])
    • 看起来dataType: "json"charset=utf-8 是可选的,因为您的解决方案可以在没有这些片段的情况下在 IE 和 Chrome 中运行
    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 2014-10-27
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多