我只是在玩 Visual Studio 2012 并尝试使用本地 SQL Server 数据库制作一个非常简单的新闻站点。问题是RequiredFieldValidator 不适用于文本框。即使这些框是空的,数据库仍然会使用空记录进行更新,我只是不知道为什么验证器在 VS2010 中工作正常。如果我按下提交按钮,则会显示错误,但数据库仍会使用空记录进行更新。有人知道为什么吗?如果这有什么不同,我在表单的 C# 文件中使用 ScriptResourceMapping。
这是我的代码:
<section id="addnews_panel">
<h2>Rubrik</h2>
<asp:TextBox ID="txtHeadlineForm1" runat="server" Width="332px" CausesValidation="True" ValidationGroup="newsForm"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtHeadlineForm1" ErrorMessage="Write something" ValidationGroup="newsForm"></asp:RequiredFieldValidator>
<h2>Rubrik 2</h2>
<asp:TextBox ID="txtHeadlineForm2" runat="server" Width="328px" CausesValidation="True" ValidationGroup="newsForm"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtHeadlineForm2" ErrorMessage="Write something" ValidationGroup="newsForm"></asp:RequiredFieldValidator>
<h2>Ingress</h2>
<asp:TextBox ID="txtIngressForm" runat="server" Height="99px" TextMode="MultiLine" Width="325px" CausesValidation="True" ValidationGroup="newsForm"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtIngressForm" ErrorMessage="Write something" ValidationGroup="newsForm"></asp:RequiredFieldValidator>
<h2>Nyhet</h2>
<asp:TextBox ID="txtNewsForm" runat="server" Height="288px" TextMode="MultiLine" Width="507px" CausesValidation="True" ValidationGroup="newsForm"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtNewsForm" ErrorMessage="Write something" ValidationGroup="newsForm"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btnAddNews" runat="server" Text="Lägg till nyhet" OnClick="btnAddNews_Click" ValidationGroup="newsForm" />
<h2>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</h2>
</section>
protected void btnAddNews_Click(object sender, EventArgs e)
{
using (dbnewsEntities db = new dbnewsEntities())
{
var addNews = new tblNews();
addNews.headline = txtHeadlineForm1.Text;
addNews.headline2 = txtHeadlineForm2.Text;
addNews.ingress = txtIngressForm.Text;
addNews.news = txtNewsForm.Text;
addNews.date = DateTime.Now.ToString();
db.tblNews.Add(addNews);
db.SaveChanges();
}
lblResult.Text = "News added!";
}