Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

jquery - Passing an JSON array to MVC Web API via GET

I know there are tons of answers for this topic, but couldn't find the solution to my issue. I have an ASP.NET MVC Web API that looks like this:

    [HttpGet]
    public IList<Country> GetCountryList(List<long> idList)

And I've tried calling it like this:

    $.ajax({
        dataType: "json",
        data: JSON.stringify({idList: listOfIds}),            
        type: "GET",
        url: "api/v1/util/CountryList",
        success: function (result) {
            alert(result);
        }
    });

The URL then looks like this:

https://localhost/supertext/api/v1/util/CountryList?{%22idList%22:[46,14,62,83,120]}

Alternative:

    $.ajax({
        dataType: "json",
        data: {
            idList: JSON.stringify(listOfIds),
        }          
        type: "GET",
        url: "api/v1/util/CountryList",
        success: function (result) {
            alert(result);
        }
    });

URL:

https://localhost/supertext/api/v1/util/CountryList?idList=%5B46%2C14%2C62%2C83%2C120%5D

Both methods don't work.

Do I really have to send and receive it as a string or use POST?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, don't try to be sending JSON in a GET request. Use JSON with other verbs which have body, such as POST and PUT.

Do it the standard way, by decorating your action parameter with the [FromUri] attribute:

public IList<Country> GetCountryList([FromUri] List<long> idList)
{
    ...
}

and then just trigger the AJAX request:

$.ajax({
    url: 'api/v1/util/CountryList',
    type: 'GET',
    data: { idList: [1, 2, 3] },
    traditional: true,
    success: function (result) {
        console.log(JSON.stringify(result));
    }
});

Further recommended reading for you about how the model binding in the Web API works:

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...