簡體   English   中英

使用jQuery設置值以將JSON發布到ASP.Net Web API 2服務

[英]Setting a value using jQuery to post JSON to an ASP.Net Web API 2 service

我有一個看似簡單的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組成的數組?

設置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);
                        }

                    });
                });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM