下拉列表选值后保存报错:JSON无法转换为List<Guid>
问题:单选分类下拉框提交时JSON转换错误
当从Category下拉列表选择单个选项并点击保存按钮时,出现如下错误:The JSON value could not be converted to System.Collections.Generic.List1[System.Guid]. Path: $.categories | LineNumber: 0 | BytePositionInLine: 377`
问题出在选中值的赋值逻辑——虽然只需要选单个选项,但当前代码的处理方式导致后端无法解析提交的数据。
相关代码
edit-tentry.component.html
<ng-container *ngIf="categories$ | async as categories"> <select class="form-control" [(ngModel)]="selectedCategories" name="categories"> <option *ngFor="let category of categories;" [value]="category.id">{{category.name}} </option> </select> </ng-container>
edit-tentry.component.ts
export class EditTentryComponent implements OnInit, OnDestroy { id: string | null = null; model?: Tentry categories$?: Observable<Category[]>; selectedCategories?: string[]; ngOnInit(): void { this.categories$ = this.categoryService.getAllCategories(); this.routeSubscription = this.route.paramMap.subscribe({ next: (params) => { this.id = params.get('id'); // 获取Tentry数据 if(this.id){ this.getTentrySubscription = this.tentryService.getTentryById(this.id).subscribe({ next: (response) => { this.model = response; this.selectedCategories = response.categories.map(x => x.id); } }); } console.log("初始化时选中的分类: ", this.selectedCategories); } }); } onFormSubmit(): void{ if(this.model && this.id) { const updateTentry: UpdateTentry = { // 其他字段... ticketStatus: this.model.ticketStatus, categories: this.selectedCategories ?? [] }; this.updateTentrySubscription = this.tentryService.updateTentry(this.id, updateTentry) .subscribe({ next:(response) => { this.router.navigateByUrl('/admin/tentry') } }); } } }
Category 接口定义
export interface Category { id: string; name: string; urlHandle: string; }
解决方案
核心问题:你用的是单选<select>,但绑定的selectedCategories是数组类型。提交时前端会把单个字符串值传给后端,而后端期望的是List<Guid>数组,所以触发了JSON转换错误。
按以下步骤修改:
- 调整变量类型
把组件里的selectedCategories从数组改成单个字符串:
// 原代码 selectedCategories?: string[]; // 修改后 selectedCategories?: string;
- 修改初始化赋值逻辑
从API获取数据时,只取第一个分类的ID(因为是单选场景):
// 原代码 this.selectedCategories = response.categories.map(x => x.id); // 修改后 this.selectedCategories = response.categories.length > 0 ? response.categories[0].id : undefined;
- 调整提交参数构造
把单个ID包装成数组,匹配后端的List<Guid>要求:
// 原代码 categories: this.selectedCategories ?? [] // 修改后 categories: this.selectedCategories ? [this.selectedCategories] : []
模板代码无需修改,单选<select>绑定单个字符串值是完全正常的。
这样修改后,提交时categories字段会是包含单个ID的数组,后端就能正确解析了。
内容的提问来源于stack exchange,提问作者Vith
相关产品推荐
相关产品推荐

