ASP.NET Core下拉列表数据绑定及表单提交时Category绑定失败问题求解
问题解决方法
根因分析
你提交的下拉框值是分类的int类型Id,默认模型绑定无法直接将int值映射为Product类里的Category复杂导航属性,导致Category字段校验失败报错。
具体修改步骤
- 修改Product模型,添加外键字段
在Product类中增加CategoryId外键属性,EF Core会按照约定自动识别该字段为Category导航属性的外键:
public class Product { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } // 新增外键字段 public int CategoryId { get; set; } public Category Category { get; set; } public decimal Price { get; set; } }
如果需要显式声明外键关联,也可以添加[ForeignKey]特性:
[ForeignKey(nameof(Category))] public int CategoryId { get; set; }
- 修改Edit.cshtml的下拉框绑定字段
将下拉框的asp-for从绑定Category改为绑定新增的CategoryId字段:
<div class="form-group"> <label asp-for="CategoryId"></label> <div> <span class="text-danger" asp-validation-for="CategoryId"></span> </div> <select asp-for="CategoryId" asp-items="ViewBag.Categories"> <option disabled>Choose the category</option> </select> </div>
可选优化(非必须)
修改EFProductRepository的SaveProduct方法,直接更新外键字段即可,不需要操作整个导航属性,执行效率更高:
if (entry != null) { entry.Title = product.Title; entry.Description = product.Description; // 直接更新外键即可 entry.CategoryId = product.CategoryId; entry.Price = product.Price; }
修改完成后重新生成项目,提交表单时分类Id就能正常绑定到CategoryId字段,校验报错会消失,EF Core会自动根据外键关联对应的Category对象。
内容的提问来源于stack exchange,提问作者tiomkin
相关产品推荐
相关产品推荐

