验证器显示,但按钮执行服务器代码

validator shows, but button executes server code

似乎有问题...我的 Web 窗体应用程序中有一个 asp 文本框,它有一个必填字段验证器。如果文本框为空,它会显示验证器,但也会执行服务器代码,在这种情况下,代码会插入 table:

<div class="form-group">
            <asp:Label ID="lblPName" runat="server" CssClass="col-md-2 control-label" Text="Category Name"></asp:Label>
            <div class="col-md-3">
                <asp:TextBox ID="txtCategoryName" runat="server" CssClass="form-control"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="text-danger" runat="server" ErrorMessage="This Field is required" ControlToValidate="txtCategoryName"></asp:RequiredFieldValidator>
            </div>
        </div>

按钮代码:

<div class="form-group">
            <div class="col-md-2"></div>
            <div class="col-md-6">
                <asp:Button ID="btnAddCategory" CssClass="btn btn-default" runat="server" Text="Add" onclick="btnAddCategory_Click" />
            </div>
        </div>

我用于插入数据的服务器端代码:

string cs = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("Insert into tblCategories values(@CategoryName)", con);
            cmd.Parameters.AddWithValue("@CategoryName", txtCategoryName.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            txtCategoryName.Text = string.Empty;
        }
        BindCategoryRepeater();

为什么会发生这样的事情?

在按钮和 RequiredFieldValidator 中添加验证组:

 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="text-danger" runat="server" ErrorMessage="This Field is required" ValidationGroup="test" ControlToValidate="txtCategoryName"></asp:RequiredFieldValidator>

 <asp:Button ID="btnAddCategory" CssClass="btn btn-default" runat="server" Text="Add" onclick="btnAddCategory_Click" ValidationGroup="test"  />

参考:RequiredFieldValidator Class

在您的服务器端代码中添加带有 Page.IsValid 的 if else

if(Page.IsValid)
{
    string cs = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand cmd = new SqlCommand("Insert into tblCategories values(@CategoryName)", con);
        cmd.Parameters.AddWithValue("@CategoryName", txtCategoryName.Text);
        con.Open();
        cmd.ExecuteNonQuery();
        txtCategoryName.Text = string.Empty;
    }
    BindCategoryRepeater();
}
else
{
    //handle the error
}