似乎有些东西被打破了...我的Web窗体应用程序中有一个asp文本框,它有一个必需的字段验证器。如果文本框为空,则显示验证程序,但也执行服务器代码,在这种情况下代码插入表中:
<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();
为什么会发生类似的事情?
答案 0 :(得分:0)
在Button和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" />
答案 1 :(得分:0)
参考: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
}