【发布时间】:2016-05-14 07:14:00
【问题描述】:
我在将 JSON 对象传递给我的 ASP.NET MVC 控制器时遇到问题。
JS中JSON是这样设置的:
jsonChildren = '{ "childImproItems" : [{ "Theme":"tralalali" }, { "Theme":"tralalali" }]}';
...
$.ajax({
url: url,
type: 'POST',
data: JSON.parse(jsonChildren),
success: function (result) {
...
},
error: function (result) {
..
}
});
在我的控制器内部:
public int MyMethod(String typeName, SelectOptionsViewModel id) {
return 0;
}
关注的Model类如下:
public class SelectOptionsViewModel {
...
public List<ChildImproItemViewModel> childImproItems { get; set; }
}
和:
public class ChildImproItemViewModel {
...
public string Theme { get; set; }
}
调试器正确地将我路由到我的控制器并将 JSON 正确解释为 SelectOptionsViewModel 实例。 它使用 2 个对象的列表正确设置其 childImproItems 属性。 但是 2 个 childImproItems 对象的 Theme 属性为 null,尽管在我的示例中它们应该设置为一个虚拟值。 其他属性也是如此。
你们知道我的错误在哪里吗?
提前谢谢。
编辑: 如果我自己创建 JSON 对象,情况完全相同:
JSONFormatChildren = {};
JSONFormatChildren.childImproItems = {};
JSONFormatChildren.childImproItems[0] = {};
JSONFormatChildren.childImproItems[0].Theme = 'trouloulou';
JSONFormatChildren.childImproItems[1] = {};
JSONFormatChildren.childImproItems[1].Theme = 'trouloulou';
然后是ajax:
$.ajax({
url: url, //We can't pass the selectId directly as C# does not know about JS variables
type: 'POST',
data: JSONFormatChildren,
....
}
再一次,使用正确数量的元素 (2) 正确创建了列表,但所有元素 Theme property = null 而不是 trouloulou...
编辑 2: 如果我使用这个 JSON:
jsonChildren = '{"Theme":"tralalali"}';
还有这个方法:
public int test2(String typeName, ChildImproItemViewModel id)
{
return 0;
}
效果很好
如果我使用这个 JSON:
jsonChildren = '[{"Theme":"tralalali"},{"Theme":"tralalali"}]';
还有这个方法:
public int test2(String typeName, List<ChildImproItemViewModel> id)
{
return 0;
}
它不起作用:调用方法时 id = null
【问题讨论】:
-
json2csharp.com 在使用 json 处理模型绑定器问题时发现有用。这会让你看到你的 json 在 C# 中解析成什么(很明显),这样你就可以看到问题是出在你的实际 json 还是其他东西上。
-
不错的 URL thx 分享:)。不过,在其中解析我的 JSON 字符串最终会得到明显正确的模型类。
-
@AD 编辑您的问题以将签名包含到您接受 JSON 的 ActionResult 中
-
@AD 我刚刚注意到的另一个问题是您的
jsonChildren试图将 JSON 构造为字符串。忘记那个。只需创建一个 Javascript 对象并将其传递给 jquery ajax 函数。我会更新我的答案 -
@AD 将 contentType: 'application/json' 添加到您的 ajax 中
标签: javascript asp.net json asp.net-mvc asp.net-mvc-3