当用户提交时,项目将通过验证。我真正遇到的问题是If
语句。我做得对吗/有没有办法更好地做这部分?
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Check Input for Validation
//Mass Validation ensure everything has a vaule
if (txtFirstName.Text == "" && txtLastName.Text == "" && txtPayRate.Text == ""
&& txtStartDate.Text == "" && txtEndDate.Text == "")
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
txtLastName.BackColor = System.Drawing.Color.Yellow;
txtPayRate.BackColor = System.Drawing.Color.Yellow;
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
return;
}
if (txtFirstName.Text != "")
{
txtFirstName.BackColor = System.Drawing.Color.White;
}
else
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
return;
}
if (txtLastName.Text != "")
{
txtLastName.BackColor = System.Drawing.Color.White;
}
else
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
return;
}
if (txtPayRate.Text != "")
{
txtPayRate.BackColor = System.Drawing.Color.White;
}
else
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
return;
}
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
}
答案 0 :(得分:1)
protected void btnSubmit_Click(object sender, EventArgs e)
{
var textBoxes = new[] { txtFirstName, txtLastName, txtPayRate, txtStartDate, txtEndDate };
var isValid = true;
foreach (var textBox in textBoxes)
{
if (textBox.Text == "")
{
isValid = false;
textBox.BackColor = System.Drawing.Color.Yellow;
}
else
{
textBox.BackColor = System.Drawing.Color.White;
}
}
if (!isValid)
return;
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
}
但是,看起来这是ASP.NET网站,所以您应该使用RequiredFieldValidator
代替。
答案 1 :(得分:0)
你可以这样做:
TextBox[] boxes = new[] { txtFirstName, txtLastName, txtPayRate,
txtStartDate, txtEndDate };
IEnumerable<TextBox> unfilledBoxes = boxes.Where(b => b.Text == "");
foreach (TextBox box in unfilledBoxes)
{
box.BackColor = System.Drawing.Color.Yellow;
}
if (!unfilledBoxes.Any())
{
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
}
答案 2 :(得分:0)
如果这是您的代码所暗示的ASP.NET WebForms,那么您应该使用Web Forms Validation。