首页 > 解决方案 > JSON 中的数组接收为空

问题描述

当我从浏览器 (JavaScript) 向 ASP.NET MVC 后端提交包含一些原始类型和一个对象数组的表单时,我正在发送一个 JSON 对象,但是对象数组被反序列化为一个空数组(实际上是列表)。

我已经使用 Chrome 的检查器检查了发送的内容,并且 JSON 以正确的值输出,所以我相信问题出在后端。

控制器动作:

[HttpPost]
public ActionResult FooAction(FooViewModel viewModel)
{
    //code
}

FooView 模型:

public class FooViewModel
{
    public List<BarViewModel> Bars { get; set; } // <-- What arrives empty, not null

    public int PrimitiveProperty { get; set; }

    public int OtherPrimitiveProperty { get; set; }

    public string LastPrimitiveProperty { get; set; }
}

条形视图模型:

public class BarViewModel
{
    public long LongProperty{ get; set; }

    public string StringProperty { get; set; }

    public bool BoolProperty { get; set; }
}

调试控制器的动作时,Bars为空(非空)。

这就是 Chrome 的检查员向我展示的内容:

LastPrimitiveProperty: SomeText
PrimitiveProperty: 1
OtherPrimitiveProperty: 9
Bars: [{"LongProperty":274,"StringProperty":"SomeString","BoolProperty":true},{"LongProperty":119,"StringProperty":"SomeString","BoolProperty":false},{"LongProperty":163,"StringProperty":"SomeString","BoolProperty":false}]

标签: javascriptc#jsonasp.net-mvc

解决方案


[HttpPost]
public ActionResult FooAction([FromBody]FooViewModel viewModel)
{
   //code
}

试试这个,它应该收集 json 对象


推荐阅读