在控制器中将JSON反序列化为嵌套视图模型 [英] Deserialising JSON into nested view model in controller
问题描述
我有一个嵌套的视图模型结构:
I have a nested view model structure:
public class PersonViewModel
{
public int Height { get; set; }
public List<LegViewModel> Legs {get;set;}
}
public class LegViewModel
{
public int Length { get; set; }
}
我使用jquery帖子向其发送一些JSON:
I send some JSON to this using jquery post:
<script>
$(function () {
$("#mybutton").click(function () {
$.ajax({
type: "POST",
data: {
Height: 23,
Legs: [
{
Length: 45,
}
]
}
});
});
});
</script>
<button id="mybutton">hello world!</button>
我要发布到此控制器操作:
I'm posting to this controller action:
[HttpPost]
public ActionResult Save(PersonViewModel model)
{
return Json(new { success = true });
}
填充PersonViewModel
的Height
,以及Legs
列表中元素的数量,但列表中的每个LegViewModel
均不填充:Length
属性保持为0,我希望Legs
数组包含一个带有Length
45的元素.
The Height
of a PersonViewModel
gets populated, as does the number of elements in the Legs
list, but each LegViewModel
in the list does not: the Length
property remains at 0 where I would expect the Legs
array to contain one element with Length
45.
请注意,当我完全不使用列表时,也是如此:具有以下内容会产生不为null的PersonViewModel.Legs property, but still as the
Legs.Length`属性,其值为0:
Note that this is also the same when I do not use a list at all: having the following yields a not null PersonViewModel.Legs property, but still as the
Legs.Length` property as 0:
// view model
public class PersonViewModel
{
public int Height { get; set; }
//public List<LegViewModel> Legs {get;set;}
public LegViewModel Leg { get; set; }
}
public class LegViewModel
{
public int Length { get; set; }
}
// view
$("#mybutton").click(function () {
$.ajax({
type: "POST",
data: {
Height: 23,
Leg:
{
Length: 45,
}
}
});
})
如何使用JSON填充嵌套视图模型?我有什么想念的吗,还是MVC不能做到这一点?
How can I populate a nested view model using JSON? Is there something I've missed or can MVC not do this?
推荐答案
如果您希望MVC Model Binder在使用$.ajax
发送数据时正确地解析您的集合,则需要做两件事:
If you want that the MVC Model Binder parses your collections properly when sending data with $.ajax
you need to do two things:
- 将
contentType
设置为'application/json'
- 并且您的
data
应该包含JSON,以便JSON.stringify
数据
- Set the
contentType
to'application/json'
- And your
data
should hold JSON soJSON.stringify
the data
因此,这里是正确的用法,然后可以由模型绑定程序进行解析:
So here is the correct usage which then can be parsed by the model binder:
$("#mybutton").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
Height: 23,
Legs: [
{
Length: 45,
}
]
})
});
});
这篇关于在控制器中将JSON反序列化为嵌套视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!