所以基本上,我的目标是做一个简单的循环,在提交时,在继续之前检查是否已经检查了一堆框。我知道如何在 PHP 或 MVC 中做到这一点,但我的老板强迫我使用 web 控件。
因此,我们到了。
Default.aspx 中的相关代码
<div>
<asp:CheckBoxList id="eligibilityreqs" runat="server">
<asp:ListItem value="item1" runat="server">I am great</asp:ListItem>
<asp:ListItem value="item2" runat="server">I am amazing.</asp:ListItem>
<asp:ListItem value="item3" runat="server">I completed EVERTHING</asp:ListItem>
<asp:ListItem value="item4" runat="server">Pies are delicious</asp:ListItem>
<asp:ListItem value="item5" runat="server">Oh man a fifth one</asp:ListItem>
</asp:CheckBoxList>
</div>
<p>
<asp:Label Text="" id="finalmessage" runat="server" />
</p>
<div>
<asp:Button Text="Submit" runat="server" onclick="process" />
</div>
Default.aspx 的代码隐藏
using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.Configuration;
using System.Data.Odbc;
using System.Web.UI.WebControls;
namespace minor
{
public partial class Default : System.Web.UI.Page
{
protected void process (object sender, EventArgs e)
{
bool valid = true;
string debugtext = "";
foreach (ListItem li in eligibilityreqs.Items) {
if (!li.Selected) {
valid = false;
debugtext = debugtext + li.Selected;
}
}
if (!valid) {
finalmessage.Text = "There has been an error, please check all boxes." + debugtext;
} else {
string conString = WebConfigurationManager.ConnectionStrings ["connectionstring"].ConnectionString;
using (OdbcConnection con = new OdbcConnection(conString)) {
string sqlstring = "SELECT yum FROM pie_application LIMIT 1;";
using (OdbcCommand com = new OdbcCommand(sqlstring, con)) {
con.Open ();
string reader = Convert.ToString (com.ExecuteScalar ());
finalmessage.Text = reader;
}
}
}
}
}
}
作为参考,调试文本的输出只是假,假,假,假,假。