ASP.NET Core 5 MVC提交复杂集合时视图模型实例化但无数据如何解决?
问题根因与解决方案
1 核心问题:serializeArray()输出格式不匹配绑定要求
serializeArray()默认生成的是[{name: "字段名", value: "字段值"}]的一维键值对数组,和你需要的GlassDemand对象数组结构完全不匹配,模型绑定系统无法把这种扁平结构映射为POCO集合。
2 必要配置:控制器参数添加[FromBody]注解
你提交的请求头为application/json,ASP.NET Core默认不会从请求体读取数据绑定到复杂类型,必须在Action参数前显式添加[FromBody]标识,示例如下:
[HttpPost] public IActionResult CreatePL([FromBody] PickListDemandVM vm) { // 业务逻辑 }
3 修正JS序列化逻辑,生成符合POCO结构的JSON
你需要把serializeArray()的扁平输出转换为和GlassDemand结构对应的对象数组,注意属性名要和POCO类定义保持一致,数字类型要做类型转换避免绑定失败,修正后的Ajax代码示例:
$('#btnCreate').click(function(e) { e.preventDefault(); const formItems = $('#plTarget').serializeArray(); const glassDemands = []; // 解析表单name属性,按索引合并为GlassDemand对象 formItems.forEach(item => { const nameMatch = item.name.match(/^GlassDemands\[(\d+)\]\.(\w+)$/); if (!nameMatch) return; const index = +nameMatch[1]; const prop = nameMatch[2]; if (!glassDemands[index]) glassDemands[index] = {}; // 数字类型属性自动转整型 if(['sequence','glassqty','pickedqty','ItemId'].includes(prop)){ glassDemands[index][prop] = +item.value || 0; return; } glassDemands[index][prop] = item.value; }); $.ajax({ type: 'POST', url: '@Url.Action("CreatePL", "Reports")', data: JSON.stringify({ GlassDemands: glassDemands }), contentType: 'application/json; charset=UTF-8', success: res => {}, error: err => {} }); });
4 嵌套集合绑定补充说明
如果你需要同时提交Box、BoxItem这类嵌套集合数据,表单字段的name属性需要符合嵌套层级命名规范,例如GlassDemands[0].Boxes[0].Selected、GlassDemands[0].Boxes[0].BoxItems[0].Qty,JS转换逻辑也要对应适配嵌套层级的解析。
内容的提问来源于stack exchange,提问作者midohioboarder
相关产品推荐
相关产品推荐

