ASP.NET注册页面提交数据无法写入Database.mdf问题求助
Let's walk through the problems in your code and fix them step by step—both frontend validation and backend database logic have critical gaps that are keeping your data from writing to Database.mdf.
Frontend ASPX Problems
First, your client-side validation has logic errors, and your form submission trigger doesn't match what your backend is checking for:
Mismatched Submit Button Name
Your submit button hasname="sub", but your backend checks forRequest.Form["submit"]—this means the backend code block that handles data insertion never runs.Broken Validation Logic
- Username/password length check uses
||instead of&&:!(length >= 6 || length <= 20)will always be false (any number is either >=6 or <=20). It should be!(length >=6 && length <=20). - Phone number validation loop uses the username's
lengthvariable instead oflengthPhone—this will cause errors if your username is longer than your phone number input. - Phone character check uses
||instead of&&:!((valuePhone.charAt(i) >= '0' || valuePhone.charAt(i) <= '9'))allows non-numeric characters. It should be!((valuePhone.charAt(i) >= '0' && valuePhone.charAt(i) <= '9')). - Phone length check doesn't
return falsewhen invalid—so the form will still submit even if the phone number isn't 10 digits.
- Username/password length check uses
Fixed ASPX Validation Script
<script> function CheckAll() { var flag = true; var username = document.getElementById('user'); var length = username.value.length; var value = username.value; // Username character check for (var i = 0; i < length; i++) { if (!((value.charAt(i) >= '0' && value.charAt(i) <= '9') || (value.charAt(i) >= 'a' && value.charAt(i) <= 'z') || (value.charAt(i) >= 'A' && value.charAt(i) <= 'Z'))) { alert("用户名只能包含字母和数字"); return false; } } // Username length check if (!(length >= 6 && length <= 20)) { alert("用户名长度必须为6-20个字符"); return false; } var password = document.getElementById('password'); var lengthPass = password.value.length; var valuePass = password.value; // Password character check for (var i = 0; i < lengthPass; i++) { if (!((valuePass.charAt(i) >= '0' && valuePass.charAt(i) <= '9') || (valuePass.charAt(i) >= 'a' && valuePass.charAt(i) <= 'z') || (valuePass.charAt(i) >= 'A' && valuePass.charAt(i) <= 'Z'))) { alert("密码只能包含字母和数字"); return false; } } // Password length check if (!(lengthPass >= 6 && lengthPass <= 20)) { alert("密码长度必须为6-20个字符"); return false; } // Email validation var x = document.forms["form"]["mail"].value; var atpos = x.indexOf("@"); var dotpos = x.lastIndexOf("."); if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) { alert("邮箱地址无效"); return false; } // Phone validation var phone = document.getElementById('phone'); var valuePhone = phone.value; var lengthPhone = valuePhone.length; for (var i = 0; i < lengthPhone; i++) { if (!((valuePhone.charAt(i) >= '0' && valuePhone.charAt(i) <= '9'))) { alert("手机号只能包含数字"); return false; } } if (lengthPhone != 10) { alert("手机号必须为10位数字"); return false; // Add this to stop submission } return true; } </script>
Backend C# Problems
Your backend code is incomplete—you're missing database connection logic, parameterized queries (to avoid SQL injection), and proper handling of form inputs. Here's a complete, fixed version:
Fixed C# Backend Code
using System; using System.Data.SqlClient; // Add this namespace for SQL Server operations public partial class Register : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Check if the submit button (name="sub") was clicked if (Request.Form["sub"] != null) { // Get form values string name = Request.Form["name"]; string username = Request.Form["username"]; string password = Request.Form["password"]; string mail = Request.Form["mail"]; string phone = Request.Form["phone"]; string date = Request.Form["date"]; string favoriteGame = Request.Form["choose"]; // Database connection string (adjust based on your setup) string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"; // SQL insert query (use parameterized queries to prevent injection) string sql = @"INSERT INTO Users (Name, Username, Password, Email, Phone, DateOfBirth, FavoriteGame) VALUES (@Name, @Username, @Password, @Email, @Phone, @DateOfBirth, @FavoriteGame)"; using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { // Add parameters cmd.Parameters.AddWithValue("@Name", name); cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@Password", password); // Note: In production, hash passwords! cmd.Parameters.AddWithValue("@Email", mail); cmd.Parameters.AddWithValue("@Phone", phone); cmd.Parameters.AddWithValue("@DateOfBirth", DateTime.Parse(date)); cmd.Parameters.AddWithValue("@FavoriteGame", favoriteGame); try { conn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); // If rows were inserted, redirect or show success message if (rowsAffected > 0) { Response.Redirect("Success.aspx"); // Create a success page or show a message } } catch (Exception ex) { // Handle errors (log them or show a user-friendly message) Response.Write("Error: " + ex.Message); } } } } } }
Important Notes
- Database Table Structure: Make sure your
Userstable (or whatever table name you use) has columns that match the parameters in the insert query (Name,Username,Password, etc.). - Password Hashing: Never store plain-text passwords in production—use a hashing library like
BCryptorASP.NET Identityto hash passwords before inserting them. - Connection String: Verify that your connection string points to the correct path of
Database.mdf. The|DataDirectory|placeholder points to theApp_Datafolder in your project. - Error Handling: In production, replace
Response.Write(ex.Message)with a user-friendly error message and log the exception details securely.
内容的提问来源于stack exchange,提问作者idan yossifov

