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

ASP.NET Core MVC创建新产品时Id始终为0的问题排查

问题原因与解决方案

核心原因

  1. 数字字段绑定错误:模型中Price、Price50、Price100为int类型,但视图中对应的input使用type="text",若输入非数字内容(或空值),会导致模型绑定失败,触发ModelState验证不通过。
  2. 冗余的Id字段提交:创建新产品时,Id由数据库自动生成,但视图中添加了隐藏的asp-for="Id"输入框,提交时会传递默认值0。虽然该值本身不会触发验证错误,但会干扰问题排查,且属于不必要的操作。

解决步骤

1. 修正数字字段的input类型

将视图中Price、Price50、Price100的input类型从text改为number,确保浏览器限制输入数字,同时提升模型绑定的准确性:

<div class="py-2">
    <input type="number" asp-for="Price" placeholder="Price for 1-50" class="form-control form-floating shadow border-0" />
    <span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="py-2">
    <input type="number" asp-for="Price50" placeholder="Price for 50+" class="form-control form-floating shadow border-0" />
    <span asp-validation-for="Price50" class="text-danger"></span>
</div>
<div class="py-2">
    <input type="number" asp-for="Price100" placeholder="Price for 100+" class="form-control form-floating shadow border-0" />
    <span asp-validation-for="Price100" class="text-danger"></span>
</div>

2. 移除冗余的Id隐藏输入框

删除视图中的<input asp-for="Id" hidden />,创建新实体时Id由EF Core自动生成,无需从表单提交。

3. (可选)显式配置主键自增

虽然EF Core默认会识别命名为Id的int字段为自增主键,但可显式添加属性确保配置正确:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace test.Models
{
    public class Product
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        // 其他字段保持不变
    }
}

4. 排查具体验证错误

调试时可在HttpPost的Create方法中添加代码,查看ModelState的具体错误信息,快速定位问题:

[HttpPost]
public IActionResult Create(Product product)
{          
    // 查看验证错误
    var validationErrors = ModelState.Values.SelectMany(v => v.Errors);
    // 可通过断点查看validationErrors的内容

    if (ModelState.IsValid)
    {
        _productRepository.Add(product);
        _productRepository.Save();

        TempData["Success"] = "Product created successfully";

        return RedirectToAction("Index");
    }

    return View();  
}

内容的提问来源于stack exchange,提问作者Miran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:08:24