ASP.NET Core MVC创建新产品时Id始终为0的问题排查
问题原因与解决方案
核心原因
- 数字字段绑定错误:模型中
Price、Price50、Price100为int类型,但视图中对应的input使用type="text",若输入非数字内容(或空值),会导致模型绑定失败,触发ModelState验证不通过。 - 冗余的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
相关产品推荐
相关产品推荐

