从Javascript将KeyValuePair或IDictionary的列表传递给Web Api控制器
我有一个web api控制器,我想发布两个参数。 一个是扁平的int ID,另一个是IDictionary或类似的等价物。
[HttpPost] public void DoStuff(int id, [FromBody]IDictionary 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控制器。 它为null或有一个伪造条目({0,0})。
我也尝试在Uri中发送词典 – 不用了。
如何将字典或键值对发送到api控制器?
您不需要数组 – 您需要一个简单的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' });
这个对我有用:
var settings = []; settings.push({ key: "setting01", value: "Value01" }); settings.push({ key: "setting02", value: "Value02" });
这真的很旧,但在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
。 然后网络api能够接收它。 希望这有助于未来的读者!
字典就像一组键值对。 你必须发送
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 things) { // ... }