c# - 通过 GET 发送到 MVC Controller 的 GUID JSON 列表在到达时为空,POST 有效

标签 c# jquery ajax json asp.net-mvc-3

我正在向我的 MVC Controller 发送一组类似 GUID 的对象:

$.ajax({
    type: 'GET',
    url: 'http://localhost:61975/Song/GetByIds',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: {
        songIds: JSON.stringify(songIds)
    },
    success: function (data) {
    },
    error: function(error) {
        console.error(error);
    }
});

在我的请求 header 中发送的数据如下所示:

songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]

我的 MVC3 Controller 方法如下所示:

[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
    SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
    IList<Song> songs = songManager.GetByIds(songIds);
    return new JsonDataContractActionResult(songs);
}

在此实现中,我收到一个非空列表对象,但它始终为空。我的错误是什么?

编辑:如果我像这样 POST 而不是 GET 它工作正常。怎么会??

$.ajax({
    type: 'POST',
    url: 'http://localhost:61975/Song/GetByIds',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        songIds: songIds
    }),
    success: function (data) {
        loadedSongs = loadedSongs;
        if (callback) {
            callback(data);
        }
    },
    error: function(error) {
        console.error(error);
    }
});

最佳答案

对于 jQuery Ajax 请求,您应该尝试将“传统”选项设置为 true。

有关详细信息,请参阅文档:http://api.jquery.com/jQuery.ajax/

你还应该删除 JSON.Stringify 部分。

你能试试这个吗?如果成功了请告诉我? 我自己进行了测试,效果很好。

$.ajax({
    type: 'GET',
    url: 'http://localhost:61975/Song/GetByIds',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    traditional: true, //// traditional option to true
    data: {
       songIds: songIds  /// no JSON.stringify
    },
    success: function (data) {
    },
    error: function(error) {
      console.error(error);
    }
});

关于c# - 通过 GET 发送到 MVC Controller 的 GUID JSON 列表在到达时为空,POST 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13964904/

相关文章:

javascript - 在php中访问从ajax传递的数组

c# - 如何按顺序初始化 C# 中的字符串数组,其值从 "AAAAAA"到 "ZZZZZZ"

c# - 如何在 ASP 下拉列表列表项中使用彩色圆圈? (没有 jQuery)

jquery - .not in jquery 不工作

javascript - 通过 http 默认为 https 的 AJAX 请求

javascript - event.keyCode 在ajax加载后没有给出向上和向下键的键码

c# - 有没有办法让 .Net JIT 或 C# 编译器优化掉空的 for 循环?

C# 将列表向下转换为 IList "special tactics"

javascript - 如何用属性显示:none来测量类的长度

jquery - 使用 jQuery 加载更多(无 AJAX/PHP)