Razor Pages表单提交无响应:数据库插入失败求助
表单提交无响应问题排查与修复
问题描述
我正在开发一个表单提交Web应用,此前功能均正常,但尝试向SQL数据库插入数据时毫无反应。数据库连接正常,但OnPost()方法完全没执行——哪怕我在方法里加了Console输出也看不到任何内容,数据库始终是空的。
相关代码
后端C#代码
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Data.SqlClient; namespace Proiectss.Pages.Clients { public class CreateModel : PageModel { public ClientInfo clientInfo = new ClientInfo(); public String errorMessage = ""; public String successMessage = ""; public void OnGet() { } public void OnPost() { Console.WriteLine("OnPost method is being executed."); clientInfo.name = Request.Form["name"]; clientInfo.email = Request.Form["email"]; clientInfo.phone = Request.Form["phone"]; clientInfo.adress = Request.Form["adress"]; if (string.IsNullOrEmpty(clientInfo.name) || string.IsNullOrEmpty(clientInfo.email) || string.IsNullOrEmpty(clientInfo.phone) || string.IsNullOrEmpty(clientInfo.adress)) { errorMessage = "All the fields are required"; return; } //salvam clientul in baza de date try { String connectionString = "Data Source=.\\sqlexpress;Initial Catalog=spital;Integrated Security=True"; using(SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); String sql = "INSERT INTO clients " + "(name, email, phone, adress) VALUES " + "(@name, @email, @phone, @adress);"; using(SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@name", clientInfo.name); command.Parameters.AddWithValue("@email", clientInfo.email); command.Parameters.AddWithValue("@phone", clientInfo.phone); command.Parameters.AddWithValue("@adress", clientInfo.adress); command.ExecuteNonQuery(); } } } catch(Exception ex) { errorMessage = "Error inserting data into the database: " + ex.Message; return; } clientInfo.name = ""; clientInfo.email = ""; clientInfo.phone = ""; clientInfo.adress = ""; successMessage = "New Client Added Correctly"; } } }
前端Razor代码
@page @model Proiectss.Pages.Clients.CreateModel @{} <br> <h2>New Client</h2> @if (Model.errorMessage.Length > 0) { <div class="alert alert-warning alert-dismissible fade shadow" role="alert"> <strong>@Model.errorMessage</strong> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="close"></button> </div> } <form method="POST"> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Name</label> <div class="col-sm-6"> <input type="text" class="form-control" name="name" value="@Model.clientInfo.name"> </div> </div> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Email</label> <div class="col-sm-6"> <input type="text" class="form-control" name="email" value="@Model.clientInfo.email"> </div> </div> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Phone</label> <div class="col-sm-6"> <input type="text" class="form-control" name="phone" value="@Model.clientInfo.phone"> </div> </div> <div class="row mb-3"> <label class="col-sm-3 col-form-label">Address</label> <div class="col-sm-6"> <input type="text" class="form-control" name="address" value="@Model.clientInfo.adress"> </div> </div> @if (Model.successMessage.Length > 0) { <div class="row mb-3"> <div class="col-sm-9"> <div class="alert alert-success alert-dismissible fade shadow" role="alert"> <strong>@Model.successMessage</strong> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="close"></button> </div> </div> </div> } <div class="row mb-3"> <div class="offset-sm-3 col-sm-3 d-grid"> <button type="submit" class="btn btn-primary">Submit</button> </div> <div class="col-sm-3 d-grid"> <a class="btn btn-outline-primary" href="/" role="button">Cancel</a> </div> </div> </form>
问题根源及修复方案
1. 字段名拼写不匹配(核心问题)
前端地址输入框的name属性是address,但后端代码中尝试获取的是Request.Form["adress"](少了一个字母d),同时clientInfo.adress也和前端输入框name不一致。这会导致后端的必填字段校验失败,直接触发errorMessage并返回,但可能因为没注意到错误提示,误以为OnPost方法没执行。
修复:
- 统一字段拼写:要么把前端输入框的
name改成adress,和后端保持一致:<input type="text" class="form-control" name="adress" value="@Model.clientInfo.adress"> - 或者更规范地将后端的
adress改为address,同时同步修改数据库表字段名、SQL语句中的字段名,确保全链路字段名统一。
2. 防伪造令牌缺失(潜在拦截原因)
Razor Pages默认启用防伪造验证,如果表单没有携带防伪造令牌,POST请求会被自动拦截,导致OnPost无法执行。
修复:
在表单内部添加防伪造令牌:
<form method="POST"> @Html.AntiForgeryToken() <!-- 原有表单内容 --> </form>
或者在页面顶部的@{}块中添加TagHelper引用,让表单自动生成令牌:
@page @model Proiectss.Pages.Clients.CreateModel @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
3. 改用模型绑定优化代码(可选)
手动从Request.Form取值容易出错,建议使用Razor Pages的自动模型绑定功能,简化代码并减少拼写错误:
public void OnPost(ClientInfo clientInfo) { Console.WriteLine("OnPost method is being executed."); if (string.IsNullOrEmpty(clientInfo.name) || string.IsNullOrEmpty(clientInfo.email) || string.IsNullOrEmpty(clientInfo.phone) || string.IsNullOrEmpty(clientInfo.adress)) { errorMessage = "所有字段均为必填项"; return; } // 后续数据库操作直接使用传入的clientInfo即可 try { string connectionString = "Data Source=.\\sqlexpress;Initial Catalog=spital;Integrated Security=True"; using(SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "INSERT INTO clients (name, email, phone, adress) VALUES (@name, @email, @phone, @adress);"; using(SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@name", clientInfo.name); command.Parameters.AddWithValue("@email", clientInfo.email); command.Parameters.AddWithValue("@phone", clientInfo.phone); command.Parameters.AddWithValue("@adress", clientInfo.adress); command.ExecuteNonQuery(); } } } catch(Exception ex) { errorMessage = "插入数据失败:" + ex.Message; return; } this.clientInfo = new ClientInfo(); successMessage = "客户端添加成功"; }
确保ClientInfo类的属性名和前端输入框的name完全一致。
内容的提问来源于stack exchange,提问作者WisdomAnimates
相关产品推荐
相关产品推荐

