添加Continent时触发ModelState错误:The id field is required
问题解决:添加Continent时出现ModelState错误“The id field is required”
问题原因
你的项目大概率启用了Nullable引用类型(.NET 6+默认启用),OnPostAsync方法的参数string id被视为非可空引用类型。当创建新Continent时,路由中没有传入id参数,导致该参数为null,触发ModelState的必填验证,从而出现错误提示。而更新操作时路由会传入id参数,所以验证通过。
解决方案
修改EditContinent.cshtml.cs中的OnPostAsync方法参数,将string id改为可空的string? id:
public async Task<IActionResult> OnPostAsync(string? id) { if (!ModelState.IsValid) { System.Diagnostics.Debug.WriteLine("ModelState is not Valid"); System.Diagnostics.Debug.WriteLine(ModelState.Values.SelectMany(v=>v.Errors)); return Page(); } if (id == null) { await _context.Continents.AddAsync(Continent); } else { _context.Attach(Continent).State = EntityState.Modified; } await _context.SaveChangesAsync(); return RedirectToPage("./Index"); }
额外检查(可选)
确保表单中的ID输入框正确绑定到Continent.ID:
- 页面中
asp-for="Continent.ID"会自动生成正确的name属性(name="Continent.ID"),确保用户输入的ID能正确绑定到Continent对象的ID属性。 - 如果用户未输入ID就提交表单,浏览器的
required属性会阻止提交,同时ModelState也会验证Continent.ID(因为它是主键,默认必填),这属于正常的验证逻辑。
内容的提问来源于stack exchange,提问作者Smarpan Sharma
相关产品推荐
相关产品推荐

