【发布时间】:2013-01-29 20:15:28
【问题描述】:
我有一个嵌套的视图模型结构:
public class PersonViewModel
{
public int Height { get; set; }
public List<LegViewModel> Legs {get;set;}
}
public class LegViewModel
{
public int Length { get; set; }
}
我使用 jquery post 向此发送一些 JSON:
<script>
$(function () {
$("#mybutton").click(function () {
$.ajax({
type: "POST",
data: {
Height: 23,
Legs: [
{
Length: 45,
}
]
}
});
});
});
</script>
<button id="mybutton">hello world!</button>
我将发布到此控制器操作:
[HttpPost]
public ActionResult Save(PersonViewModel model)
{
return Json(new { success = true });
}
PersonViewModel 的 Height 被填充,Legs 列表中元素的 number 个也被填充,但列表中的每个 LegViewModel 都没有:Length属性保持为 0,我希望 Legs 数组包含一个具有 Length 45 的元素。
请注意,当我根本不使用列表时,这也是相同的:具有以下将产生一个不为空的PersonViewModel.Legs property, but still as theLegs.Length` 属性为 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 不能做到这一点的吗?
【问题讨论】:
标签: asp.net-mvc json viewmodel