ASP.NET Core 3接收Angular 10 POST请求时City对象为空问题
问题原因
你后端C#的city模型中countyId定义为Dictionary<string, string>类型,但前端Angular提交的countyId是FormArray生成的对象数组,结构为[{id: "xxx"}, {id: "yyy"}],前后端数据结构不匹配导致ASP.NET Core模型绑定失败,因此接收到的city对象为null。
解决方法
方案1:保持后端Dictionary结构,前端提交前转换数据
修改Angular组件的submit方法,将countyId的数组结构转换为后端需要的键值对字典结构:
submit() { const formRawValue = this.form.getRawValue(); // 转换为后端需要的Dictionary<string, string>结构 const countyIdMap: Record<string, string> = {}; formRawValue.countyId.forEach((countyItem: {id: string}, index: number) => { // 可根据业务需求自定义字典的key,这里用索引作为示例 countyIdMap[index.toString()] = countyItem.id; }); // 组装最终提交的数据 const postData = { ...formRawValue, countyId: countyIdMap }; this.cityservice.create(postData).subscribe(res => { console.log('city created successfully!'); this.router.navigateByUrl('/Home'); }) }
方案2:调整后端模型为列表类型(更贴合存储ID列表的业务需求)
如果你的业务本质是存储多个county的ID列表,直接修改后端模型更简单合理:
public class city { [BsonId] [BsonIgnoreIfDefault] [BsonRepresentation(BsonType.ObjectId)] public string id { get; set; } public string name { get; set; } // 将Dictionary改为List<string>存储ID列表 public List<string> countyId { get; set; } }
对应前端仅需提取ID数组即可:
submit() { const formRawValue = this.form.getRawValue(); const countyIdList = formRawValue.countyId.map((item: {id: string}) => item.id); const postData = { ...formRawValue, countyId: countyIdList }; this.cityservice.create(postData).subscribe(res => { console.log('city created successfully!'); this.router.navigateByUrl('/Home'); }) }
排查技巧
遇到类似模型绑定失败问题时,可先通过浏览器F12开发者工具的「网络」面板查看请求的Payload结构,和后端模型定义对比,就能快速定位结构不匹配的问题。
内容的提问来源于stack exchange,提问作者Dark Storm
相关产品推荐
相关产品推荐

