传递一个关联数组使用JSON:期待在控制器哪种类型? [英] Passing an associative array using json: which type to expect in the controller?
问题描述
在客户端我有一个关联数组,其中我店GUID - INT对。
我使用JSON数组传递到服务器:
On the client side I have an associative array where I store "Guid" - "int" pairs. I pass the array to the server by using json:
$.ajax({
url: methodUrl,
type: 'POST',
async: false,
data: { values: items },
dataType: 'json',
success: function (data) {
//...
}
});
我试图通过这个样子的对象(从Chrome中的调试器拍摄):
The object I try to pass looks like this(taken from Chrome debugger):
items: Object
44f871e0-daee-4e1b-94c3-76d633a87634: 1
698ce237-3e05-4f80-bb0d-de948c39cd96: 1
在控制器我有一个方法
public ActionResult Method(Dictionary<Guid, int> values)
{
}
然而,属性值仍然为空。只需在控制器的所有客户端和列表GUID的列表正常工作。
我怀疑,我应该选择另一种类型的控制器,而不是字典值。
我也试图加入传统:真正的!没有成功Ajax请求,但是
However, property values remains null. With just a list of Guids on the client side and List in the controller everything works fine. I suspect that I should choose another type for values in the controller, not Dictionary. I also tried adding "traditional: true" to the ajax request, however with no success.
任何建议表示赞赏。
推荐答案
这是我使用POST命令时做的:
This is what I do when using a POST command:
var data = {
values: items
}
var obj = $.toJSON(data);
$.ajax({
url: methodUrl,
type: 'POST',
async: false,
data: obj,
dataType: 'json',
success: function (data) {
//...
}
});
这应该通过正确发送到您的控制器,你不应该使用Dictionary对象,你应匹配从客户端对象到服务器端。我会使用,有一个的Guid
和 INT
作为它的属性,并使用自定义对象 - 。 NET将匹配两间。话虽这么说,这是完全合理的使用字典,但是这是个人喜好。
This should send through to your Controller properly and you shouldn't have to use a Dictionary object, you should match objects up from client side to server side. I'd use a custom object that has a Guid
and a int
as properties in it, and use that - .NET will match the two up. That being said, it's perfectly reasonable to use a Dictionary, but that's personal preference.
即
public CustomObject
{
public Guid MyGuid { get; set; }
public int MyNumber { get; set; }
}
public ActionResult Method(List<CustomObject> values)
{
}
通过多个参数:
items.SecondNumber = yourVariable;
// In reality, you'd have a loop around your items and set this SecondNumber.
var data = {
values: items
}
var obj = $.toJSON(data);
public CustomObject
{
public Guid MyGuid { get; set; }
public int MyNumber { get; set; }
public int SecondNumber { get; set; } // This is why we use CustomObject
}
这篇关于传递一个关联数组使用JSON:期待在控制器哪种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!