在客户端,我有一个关联数组,用于存储“Guid”-“int”对。 我使用 json 将数组传递给服务器:
$.ajax({
url: methodUrl,
type: 'POST',
async: false,
data: { values: items },
dataType: 'json',
success: function (data) {
//...
}
});
我尝试传递的对象看起来像这样(取自 Chrome 调试器):
items: Object
44f871e0-daee-4e1b-94c3-76d633a87634: 1
698ce237-3e05-4f80-bb0d-de948c39cd96: 1
在 Controller 中我有一个方法
public ActionResult Method(Dictionary<Guid, int> values)
{
}
但是,属性值仍然为空。在客户端只有一个 Guids 列表,在 Controller 中有一个 List 一切正常。 我怀疑我应该为 Controller 中的值选择另一种类型,而不是字典。 我还尝试在 ajax 请求中添加“traditional: true”,但没有成功。
感谢任何建议!
最佳答案
这是我在使用 POST 命令时所做的:
var data = {
values: items
}
var obj = $.toJSON(data);
$.ajax({
url: methodUrl,
type: 'POST',
async: false,
data: obj,
dataType: 'json',
success: function (data) {
//...
}
});
这应该正确地发送到您的 Controller ,您不必使用字典对象,您应该将对象从客户端匹配到服务器端。我将使用具有 Guid
和 int
作为属性的自定义对象,并使用它 - .NET 会将两者匹配起来。话虽如此,使用字典是完全合理的,但这是个人喜好。
即
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
}
关于c# - 使用 json 传递关联数组 : which type to expect in the controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949857/