Csharp/C#教程:从Javascript将KeyValuePair或IDictionary的列表传递给Web Api控制器分享


从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: thingsdata: '=' + 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' }); 

和这样的行动

上述就是C#学习教程:从Javascript将KeyValuePair或IDictionary的列表传递给Web Api控制器分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  public ActionResult DoStuff(int id, Dictionary things) { // ... } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1019932.html

(0)
上一篇 2022年1月4日
下一篇 2022年1月4日

精彩推荐