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

ASP.NET保存按钮未校验空字段:数据仍存入SQL表问题

问题分析与修复方案

核心问题

  1. 数据库操作顺序错误:你现在是先执行SQL插入,再做字段校验——不管字段空不空,数据已经提前存进数据库了。
  2. 校验逻辑错误:用了&&(逻辑与),只有当DropDownList1、DropDownList2、TextBox1全部为空时才提示,单个或部分字段为空根本不会触发校验。
  3. 遗漏必填字段校验:代码里插入了DropDownList3和DropDownList4的值,但校验逻辑里没包含这两个字段。
  4. SQL注入风险:直接拼接用户输入到SQL语句里,很容易被注入攻击。

修复后的代码

protected void Button1_Click(object sender, EventArgs e)
{
    // 1. 先做所有必填字段的校验
    if (string.IsNullOrEmpty(DropDownList1.SelectedValue) || 
        string.IsNullOrEmpty(DropDownList2.SelectedValue) || 
        string.IsNullOrEmpty(TextBox1.Text) || 
        string.IsNullOrEmpty(DropDownList3.SelectedValue) || 
        string.IsNullOrEmpty(DropDownList4.SelectedValue))
    {
        Label1.Text = "请填写所有字段";
        return; // 校验不通过,直接终止方法
    }

    // 2. 校验通过后执行数据库操作(用参数化查询避免SQL注入)
    using (SqlConnection con = new SqlConnection("Data Source=ucpdapps2;Initial Catalog=OnCallWeb;Integrated Security=True"))
    {
        string sql = "Insert into Dispatcher_Roles values (@Val1, @Val2, @Val3, @Val4, @Val5)";
        SqlCommand comm = new SqlCommand(sql, con);
        // 添加参数
        comm.Parameters.AddWithValue("@Val1", DropDownList1.SelectedValue);
        comm.Parameters.AddWithValue("@Val2", DropDownList2.SelectedValue);
        comm.Parameters.AddWithValue("@Val3", TextBox1.Text);
        comm.Parameters.AddWithValue("@Val4", DropDownList3.SelectedValue);
        comm.Parameters.AddWithValue("@Val5", DropDownList4.SelectedValue);

        con.Open();
        comm.ExecuteNonQuery();
    } // using块会自动关闭连接,无需手动Close()

    // 3. 操作成功后的提示与清空
    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('添加成功');", true);
    ClearAllData();
}

关键修复点说明

  • 校验前置:把字段校验放在方法最开头,只要有一个必填字段为空,直接提示并终止后续操作,不会执行数据库插入。
  • 修正逻辑运算符:用||(逻辑或)代替&&,只要任意一个字段为空就触发校验提示。
  • 补全校验字段:把DropDownList3和DropDownList4也加入校验,确保所有要插入的字段都不为空。
  • 参数化SQL:用@参数名的方式代替字符串拼接,彻底避免SQL注入风险,同时也能处理特殊字符的问题。
  • using语句管理连接:用using包裹SqlConnection,会自动释放连接资源,比手动Close()更安全可靠。
  • 代码块修正:原来的else后只有提示语句,ClearAllData()不在else块里,不管校验结果都会执行,现在调整后只有校验通过才会执行成功提示和清空操作。

内容的提问来源于stack exchange,提问作者Walter G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:12:45