我有以下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>
和输入模型类
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)" />
提交后JsonCustomers 的内容
[{"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"}]
客户类别
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 ,我不知道为什么。
答案 0 :(得分:0)
在@Alex Riabov的帮助下,并基于此讨论https://github.com/aspnet/Mvc/issues/5760
model.Customers = JsonConvert.DeserializeObject<IEnumerable<InputCustomer>>(model.JsonCustomers);
在控制器动作中起到了作用。