JavaScript创建对应C#类并传递列表到ASP.NET MVC控制器的正确方法
问题根因
你当前接收为null的核心原因是JSON结构和后端C#模型不匹配,具体问题如下:
- 多封装了一层多余的
VesselDetails类,序列化后结构变成VesselDetails: { VesselDetails: [xxx,xxx] },比后端要求的结构多嵌套了一层,模型绑定失败 MainModel初始声明的VesselDetails是对象类型,和后端要求的List(对应JS数组)类型不符- 手动拼接JSON字符串容易出现格式错误,稳定性差
- 后端控制器接收JSON请求的参数没有加
[FromBody]特性,默认会按表单格式绑定,也会返回null
修正后的Vessel相关JS实现与提交代码
JS类定义
// 对应C# VesselDetail类 class VesselDetail { constructor(VesselName, VesselData) { this.VesselName = VesselName; this.VesselData = VesselData; } } // 对应C# MainModel类 class MainModel { constructor() { // 直接声明为数组,和后端List结构对齐 this.VesselDetails = []; } // 封装添加方法,不需要额外的VesselDetails类 addVessel(VesselName, VesselData) { this.VesselDetails.push(new VesselDetail(VesselName, VesselData)); } }
提交代码
let model = new MainModel(); model.addVessel("vesselName1", "vessel desc"); model.addVessel("vesselName2", "vessel desc1"); $.ajax({ url: url, type: 'POST', // 直接序列化整个对象,避免手动拼接的格式错误 data: JSON.stringify(model), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (result) { // 处理成功逻辑 }, error: function (request) { // 处理错误逻辑 } });
后端控制器写法
[HttpPost] public IActionResult YourAction([FromBody] MainModel mainModel) { // 此处可正常获取VesselDetails列表 return Json(new { success = true }); }
Attachment、Report对应的JS实现与提交方式
JS类定义
// 对应C# Attachment类 class Attachment { constructor(FileName, FileType) { this.FileName = FileName; this.FileType = FileType; } } // 对应C# Report类 class Report { constructor(ReportName) { this.ReportName = ReportName; this.Attachments = []; } addAttachment(FileName, FileType) { this.Attachments.push(new Attachment(FileName, FileType)); } }
提交代码
let report = new Report("2024年度运营报告"); report.addAttachment("运营数据.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); report.addAttachment("统计图表.png", "image/png"); $.ajax({ url: '你的接口地址', type: 'POST', data: JSON.stringify(report), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(res) { // 处理返回结果 } });
后端控制器写法
[HttpPost] public IActionResult SaveReport([FromBody] Report report) { // 此处可正常获取ReportName和Attachments列表 return Json(new { success = true }); }
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

