收到 json 自动映射到输入模型

recieved json automapping into input model

我有以下 html 表格

<input type="hidden" name="JsonCustomers" data-bind="value: ko.toJSON(customers)" />
<input type="hidden" name="JsonMaterials" data-bind="value: ko.toJSON(materials)" />
<button type="submit" class="btn btn-sm btn-primary">Submit</button>

并输入模型class

public class SubmitViewModel
{
    public string JsonCustomers { get; set; }
    public string JsonMaterials { get; set; }
}

控制器动作

[HttpPost]
public IActionResult Submit(SubmitViewModel model)
{
    throw new NotImplementedException();
}

可以自动映射 Json 成这样的东西吗?

public class SubmitViewModel
    {
        public IEnumerable<InputCustomer> Customers { get; set; }
        public IEnumerable<InputMaterial> Materials { get; set; }
    }

我想跳过从 Json 到集合的转换步骤,最好使用带有 ModelState.IsValid 函数的数据注释。有什么想法吗?

更新

html

<input type="hidden" name="JsonCustomers" data-bind="value: ko.toJSON(customers)" />
<input type="hidden" name="JsonMaterials" data-bind="value: ko.toJSON(materials)" />
<input type="hidden" name="Customers" data-bind="value: ko.toJSON(customers)" />
<input type="hidden" name="Materials" data-bind="value: ko.toJSON(materials)" />

表单提交后Json客户的内容

[{"isChecked":true,"name":"CompanyA","volume":"80","expectedDateOfOrder":"1.1.2018"},{"isChecked":true,"name":"CompanyB","volume":"100","expectedDateOfOrder":"2.2.2018"},{"isChecked":true,"name":"CompanyC","volume":"150","expectedDateOfOrder":"3.3.2018"}]

客户class

public class Customer
    {
        public bool? IsChecked { get; set; }
        public string Name { get; set; }
        public string Volume { get; set; }
        public string ExpectedDateOfOrder { get; set; }
    }

问题是 public IEnumerable<Customer> Customers 集合有 Count = 0,我不知道为什么。

这是来自 FormCollection

在@Alex Riabov 的帮助下并基于此讨论 https://github.com/aspnet/Mvc/issues/5760

model.Customers = JsonConvert.DeserializeObject<IEnumerable<InputCustomer>>(model.JsonCustomers);

在控制器操作中成功了。