C# 将字典传递给控制器 asp.net mvc
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1999525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass dictionary to controller asp.net mvc
提问by ddd
I am wanting to pass a dictionary of type <int,int>
to my controller via an Ajax post.
The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.
我想<int,int>
通过 Ajax 帖子将类型字典传递给我的控制器。这里的主要原因是帖子在这里可能有 1-3 个键值对(这些值在编译时都不知道),将来可能会增加到 5 个。
Also in the post I have to pass in some other data, such as Id and name, which all works as normal.
同样在帖子中,我必须传入一些其他数据,例如 Id 和 name,它们都可以正常工作。
How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?
我将如何在 javascript 中构建这个字典,然后通过 JQuery 帖子发送它并最终在控制器上接收它以进行处理?
Edit 2: I have decided to just solve this with a post for each value instead of trying to pass a dictionary.
编辑 2:我决定通过为每个值发布一个帖子来解决这个问题,而不是尝试传递字典。
EDIT: Here is my source for the function so you can see what I am trying:
编辑:这是我的功能来源,因此您可以看到我正在尝试的内容:
function BindAddMenuItem() {
$(".AddMenuItem").click(function (e) {
e.preventDefault();
//get header id from link by removing addmenuitem from this.id
var currentId = $(this).attr("id").replace("AddMenuItem", "");
//get itemnumber, itemname, itemdetails from textboxes with same header id
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
var itemName = jQuery.trim($("#ItemName" + currentId).val());
var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());
var costs = new Object();
//select all textboxes with class "Header" + currentId
$(".Header" + currentId).each(function (i) {
var optionId = $(this).attr("id").replace("Option", "");
costs[optionId] = $(this).val();
});
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuItem",
data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
var newNum = parseInt(itemNumber) + 1;
$("#ItemNumber" + currentId).val(newNum);
BindAllBehaviours();
}
});
});
}
回答by Jan Jongboom
Something like (javascript)
像(javascript)
dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;
$.post('/client.mvc/mypostaction/', { myDictionary: dict });
You can then post the dict
object to your controller using a Dictionary<int, int>
as property type.
然后,您可以dict
使用Dictionary<int, int>
as 属性类型将对象发布到您的控制器。
ActionResult MyPostAction(Dictionary<string, int> myDictionary)
edit from author's code second time:
第二次编辑作者的代码:
The following works for me, when having a Dictionary<string, int> kvPairs
. <int, int>
isn't going to work after all.
当有一个Dictionary<string, int> kvPairs
. <int, int>
毕竟不会工作。
Make your post like:
让你的帖子像:
var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;
$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); });
回答by VajNyiaj
Client (JavaScript):
客户端(JavaScript):
var dict = new Object();
dict.Key1 = "Value1"
dict.Key2 = "Value2"
$.post('/YourController/YourAction/', dict);
NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.
注意:“dict”对象在发送到您的操作之前会在幕后序列化。
Server:
服务器:
public ActionResult YourAction()
{
string postData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
postData = sr.ReadToEnd();
}
//Load post data into JObject (Newtonsoft.Json)
JObject o = JObject.Parse(postData);
//Extract each key/val
string val1 = (string)o["Key1"];
//Do whatever....
}
回答by mczers
JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue>
is expected. Example:
JavaScript 对象/字典必须在Dictionary<TKey, TValue>
预期时作为键值对列表传递给 ASP.NET MVC 控制器。例子:
If you have a dictionary like this:
如果你有这样的字典:
public Dictionary<string, decimal?> SomeMapping { get; set; }
then you have to use something like this in your JavaScript:
那么你必须在你的 JavaScript 中使用这样的东西:
var sourceMapping = { a: 1, b: 1.5, c: null };
var SomeMapping = [];
for (var key in sourceMapping) {
if (sourceMapping.hasOwnProperty(key)) {
SomeMapping.push({ Key: key, Value: sourceMapping[key] });
}
}
I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json'
(this may or may not be important in your case).
我在异步 POST 请求(使用 jQuery 发送)中使用了这种方法,该请求的内容类型设置为'application/json'
(这在您的情况下可能重要也可能不重要)。