You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:35:30