ASP.NET MVC提交按钮失效:无法向数据库提交新数据
ASP.NET MVC提交按钮无法存入数据库的排查与解决
视图代码的明显问题
首先看你提供的视图代码,存在两个直接错误:
- 表单的
method属性值有多余空格:原代码里method=" post"应该改为method="post",空格会导致浏览器无法正确识别POST请求方法,服务器可能将请求当作GET处理,无法触发对应的提交逻辑。 - 缺少防伪令牌:ASP.NET MVC默认启用防伪验证,表单中必须添加
@Html.AntiForgeryToken(),否则请求会被服务器拦截,无法进入提交Action。
修正后的视图代码:
@model Student <form method="post"> @Html.AntiForgeryToken() <div class="border p-3 mt-4"> <div class="row pb-2"> <h2 class="text-secondary">New Applicant</h2> <hr/> </div> <div class="mb-3"> <label asp-for="FName">First Name</label> <input asp-for="FName" class="form-control" /> <span asp-validation-for="FName" class="text-danger"></span> </div> <div class="mb-3"> <label asp-for="LName">Last Name</label> <input asp-for="LName" class="form-control" /> <span asp-validation-for="LName" class="text-danger"></span> </div> <div class="mb-3"> <label asp-for="DOB">Date of Birth</label> <input asp-for="DOB" class="form-control" /> <span asp-validation-for="DOB" class="text-danger"></span> </div> <div class="mb-3"> <label asp-for="City">City</label> <input asp-for="City" class="form-control" /> <span asp-validation-for="City" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary" style="width:150px">Create</button> <a asp-controller="Student" asp-action="Index" class="btn btn-secondary" style="width:150px"> Back to list </a> </div> </form>
注:额外添加了asp-validation-for标签,用于显示模型验证错误,方便排查用户输入问题
控制器Action检查
确保你的StudentController中有对应的POST提交Action,示例代码如下:
using System.Web.Mvc; using YourProjectName.Models; using YourProjectName.Data; public class StudentController : Controller { private readonly YourDbContext _context; public StudentController(YourDbContext context) { _context = context; } // GET: Student/Create public ActionResult Create() { return View(); } // POST: Student/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Student student) { if (ModelState.IsValid) { _context.Students.Add(student); _context.SaveChanges(); return RedirectToAction("Index"); } // 模型验证失败,返回视图显示错误 return View(student); } }
需要注意:
- Action必须标记
[HttpPost]特性,明确处理POST请求 - 必须添加
[ValidateAntiForgeryToken]特性,和视图中的@Html.AntiForgeryToken()对应 - 检查
ModelState.IsValid,确保模型绑定和验证通过 - 调用
_context.SaveChanges()完成数据库写入操作
其他排查点
- 数据库连接字符串:确认Web.config中的连接字符串正确,数据库服务正常运行
- 模型属性匹配:Student模型的属性名称(FName、LName等)必须和数据库表字段完全匹配,或者通过DataAnnotation配置映射
- 权限问题:确认应用程序池账户有数据库的写入权限
内容的提问来源于stack exchange,提问作者Ranmeet Kaur
相关产品推荐
相关产品推荐

