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

ASP.NET注册页面提交数据无法写入Database.mdf问题求助

Troubleshooting Your Registration Data Insert Issue

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:

  1. Mismatched Submit Button Name
    Your submit button has name="sub", but your backend checks for Request.Form["submit"]—this means the backend code block that handles data insertion never runs.

  2. 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 length variable instead of lengthPhone—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 false when invalid—so the form will still submit even if the phone number isn't 10 digits.

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

  1. Database Table Structure: Make sure your Users table (or whatever table name you use) has columns that match the parameters in the insert query (Name, Username, Password, etc.).
  2. Password Hashing: Never store plain-text passwords in production—use a hashing library like BCrypt or ASP.NET Identity to hash passwords before inserting them.
  3. Connection String: Verify that your connection string points to the correct path of Database.mdf. The |DataDirectory| placeholder points to the App_Data folder in your project.
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:11:43