16

我有一个 web api 控制器,我想向其发布两个参数。一个是 flat int ID,另一个是 IDictionary 或类似的等效项。

[HttpPost]
public void DoStuff(int id, [FromBody]IDictionary<int, int> things)
{
}

var things = new Array();
things.push({ 1: 10 }); // tried things.push({ Key: 1, Value: 10 })
things.push({ 2: 11 });
$.ajax({
    url: '/api/DoStuff?id=' + id,
    data: '=' + JSON.stringify(things), // tried what seems like 100 different things here
    type: 'POST',
    dataType: 'json'
});

无论我在数据参数 ( data: things, data: '=' + things) 中尝试什么,字典都不会通过 api 控制器。它要么为空,要么有一个虚假条目 ({0, 0})。

我还尝试在 Uri 中发送字典 - 不行。

如何将字典或键值对发送到 api 控制器?

4

4 回答 4

23

您不需要数组 - 您需要一个简单的 JS 对象(映射到字典)。此代码应该可以工作:

var things = {};
things['1'] = 10;
things['2'] = 11;
$.ajax({
    url: '/api/DoStuff?id=' + id,
    data: JSON.stringify(things),
    contentType: 'application/json'
    type: 'POST',
    dataType: 'json'
});
于 2013-05-14T22:38:01.697 回答
4

这个对我有用:

var settings = [];
settings.push({ key: "setting01", value: "Value01" });
settings.push({ key: "setting02", value: "Value02" });
于 2016-08-29T22:59:31.657 回答
0

这真的很旧,但是在 JS 中我创建了一个像 @cesardaniel 这样的对象:

var dictionary = [];
dictionary.push({ key: 1, value: [1,2,3,4,5] });
dictionary.push({ key: 2, value: [6,7,8,9,0] });

但我在.net 中的对象形状是类型Dictionary<KeyValuePair<int, IEnumerable<int>>。然后 web api 就可以获取它了。希望这对未来的读者有所帮助!

于 2017-07-19T17:58:05.963 回答
-1

字典就像一个键值对数组。你必须发送

var data = {}
data['things[0].Key'] = x
data['things[0].Value'] = y
// etc

编辑:

你的 js 应该看起来像这样

    var data = { };
    data['things[0].Key'] = 1;
    data['things[0].Value'] = 1;
    data['things[1].Key'] = 22;
    data['things[1].Value'] = 12;

    $.ajax({
        url: /api/DoStuff?id=' + id,
        data: data,
        type: 'POST',
        dataType: 'json'
    });

并采取这样的行动

    public ActionResult DoStuff(int id, Dictionary<int, int> things)
    {
        // ...
    }
于 2013-05-14T22:06:25.583 回答