从Javascript将KeyValuePair或IDictionary的列表传递给Web Api控制器

use*_*582 13 javascript c# ajax asp.net-web-api

我有一个web api控制器,我想发布两个参数.一个是扁平的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'
});
Run Code Online (Sandbox Code Playgroud)

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

我也尝试在Uri中发送词典 - 不用了.

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

car*_*ira 18

您不需要数组 - 您需要一个简单的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'
});
Run Code Online (Sandbox Code Playgroud)

  • 从我的答案中的`data`参数的开头有一个额外的'='(我刚编辑它以删除它).删除后,它应该工作.基本上,请求(尝试在fiddler或浏览器的开发人员工具中看到它)的主体应该是`{"1":10,"2":11}`.如果这就是你所拥有的,那么参数应该正确绑定到字典. (2认同)
  • 我花了一些时间才开始工作。我在进行 GET 调用 [FromUri] 并且在切换到 POST [FromBody] 之前无法让它工作。然后它起作用了!:-) (2认同)