c# - 如果未提交选择,单选按钮返回错误答案
问题描述
我正在使用以下代码使用 ASP.NET 和 SQL Server 2008 进行在线测验。如果在按下提交后没有检查任何内容,我需要我的单选按钮返回错误答案。
<div id="questionsdiv" runat="server" >
<asp:Label ID="lblalert" runat="server" ForeColor="Red" Font-Size="20px" Visible="false" /><br />
<asp:Repeater ID="questionsrpt" runat="server" OnItemDataBound="questionsrpt_ItemDataBound" >
<ItemTemplate>
<asp:HiddenField ID="hfID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "id")%>' Visible="false" />
<asp:RequiredFieldValidator ID="rfvquiz" runat="server" Display="Dynamic" ControlToValidate="rbloptions" ValidationGroup="quizvalidation" ForeColor="Red" Text="*" SetFocusOnError="true"/> <asp:Label ID="lblquestion" runat="server" Font-Size="20px" Text='<%# DataBinder.Eval(Container.DataItem, "title")%>' /><br />
<asp:RadioButtonList ID="rbloptions" runat="server" ValidationGroup="quizvalidation" Font-Size="14px" style="font-weight:bold"/>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" Text="Submit" ValidationGroup="quizvalidation" />
</div>
后面的代码
//quiz answers submitted
protected void btnsubmit_Click(object sender, EventArgs e)
{
SqlDataReader dReader;
string email = "";
string name = "";
string selectedanswer = "";
string correctanswer = "";
int questionId = 0;
int questionscount = 0;
int correctcount = 0;
int wrongcount = 0;
int success = 0;
ArrayList answersList = new ArrayList();
Page.Validate();
if (Page.IsValid)
{
email = txtemail.Text.Trim();
name = txtname.Text.Trim();
//check if this account has already taken the quiz.
DataTable accounts = new DataTable();
SqlCommand checkentrycmd = new SqlCommand("select * from " + quizresponsestable + " where quizid=@quizid and email=@email");
checkentrycmd.Parameters.AddWithValue("quizid", quizId);
checkentrycmd.Parameters.AddWithValue("email", email);
db checkentry = new db();
accounts = checkentry.returnDataTable(checkentrycmd);
if (accounts.Rows.Count > 0)
{
quizdetails.Visible = false;
detailsdiv.Visible = false;
questionsdiv.Visible = false;
lblmessage.Visible = true;
lblmessage.Text = "You have already taken this quiz!";
}
else
{
foreach (RepeaterItem item in questionsrpt.Items)
{
// Checking the item is a data item
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
//get the questionid
var hfId = item.FindControl("hfID") as HiddenField;
questionId = Convert.ToInt32(hfId.Value);
//get the submitted answer
var rdbList = item.FindControl("rbloptions") as RadioButtonList;
selectedanswer = rdbList.SelectedValue;
//disable to prevent submitting again
rdbList.Enabled = false;
//get the correct answer
SqlCommand getanswercmd = new SqlCommand("select optionid from " + quizquestionanswertable + " where questionid=@questionid");
getanswercmd.Parameters.AddWithValue("questionid", questionId);
db getanswer = new db();
dReader = getanswer.returnDataReader(getanswercmd);
if (!dReader.HasRows)
{
//can't find this question/answer
}
else
{
while (dReader.Read())
{
correctanswer = dReader["optionid"].ToString();
}
}
//compare both answers
if (selectedanswer == correctanswer)
{
correctcount++;
rdbList.SelectedItem.Attributes.Add("style", "color: #006400");
}
else
{
wrongcount++;
rdbList.SelectedItem.Attributes.Add("style", "color: #ff0000");
rdbList.Items.FindByValue(correctanswer).Attributes.Add("style", "color: #006400");
}
//add the submitted answer to list
answersList.Add(new string[] { questionId.ToString(), selectedanswer });
}
}
//create entry
SqlCommand insertentrycmd = new SqlCommand("insert into " + quizresponsestable + " (quizid, email, name, correctanswers, wronganswers, lastupdated) values (@quizid, @email, @name, @correctanswers, @wronganswers, @lastupdated);SELECT CAST(scope_identity() AS int)");
insertentrycmd.Parameters.AddWithValue("quizid", quizId);
insertentrycmd.Parameters.AddWithValue("email", email);
insertentrycmd.Parameters.AddWithValue("name", name);
insertentrycmd.Parameters.AddWithValue("correctanswers", correctcount);
insertentrycmd.Parameters.AddWithValue("wronganswers", wrongcount);
insertentrycmd.Parameters.AddWithValue("lastupdated", updatedate);
db insertentry = new db();
success = insertentry.ReturnIDonExecuteQuery(insertentrycmd);
//display the result on screen
if (success > 0)
{
foreach (string[] arr in answersList)
{
SqlCommand insertresponsecmd = new SqlCommand("insert into " + quizuserreponsetable + " (responseid, questionid, optionid, lastupdated) values (@responseid, @questionid, @optionid, @lastupdated)");
insertresponsecmd.Parameters.Clear();
insertresponsecmd.Parameters.AddWithValue("responseid", success);
insertresponsecmd.Parameters.AddWithValue("questionid", arr[0].ToString());
insertresponsecmd.Parameters.AddWithValue("optionid", arr[1].ToString());
insertresponsecmd.Parameters.AddWithValue("lastupdated", updatedate);
db insertresponses = new db();
insertresponses.ExecuteQuery(insertresponsecmd);
}
detailsdiv.Visible = false;
questionscount = correctcount + wrongcount;
lblalert.Visible = true;
//get the completion description from database table
SqlDataReader Treader;
SqlCommand getcompletiondesc = new SqlCommand("select completiondescription from " + quizdetailstable + " where id=@quizid");
getcompletiondesc.Parameters.AddWithValue("quizid", quizId);
db getdesc = new db();
Treader = getdesc.returnDataReader(getcompletiondesc);
if (!Treader.HasRows)
{
lblalert.Text = "Thanks for taking the Quiz." + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
}
else
{
while (Treader.Read())
{
string completiondesc = Treader["completiondescription"].ToString();
lblalert.Text = completiondesc + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
}
}
btnsubmit.Visible = false;
}
else
{
lblalert.Visible = true;
lblalert.Text = "Sorry! we could not process your request. Please try again.";
}
}
}
else
{
lblalert.Visible = true;
lblalert.Text = "Please answer all the questions!";
}
}
解决方案
我的一个问题是:如果您从 SelectedValue 的空字符串开始,为什么不检查确保 string.IsNullOrEmpty() 对所讨论的值失败?Page.IsValid() 方法将返回“true”,因为就它而言,它用于确定页面是否经过验证的信息是完整的。
这部分是免费的:(恕我直言)如果您要使用 ValidationGroup,也请使用 ValidationSummary。这样,您就不必担心单个标签
推荐阅读
- java - 无法为分离的片段创建 ViewModelProvider - 如何在 AsyncTask 的 postExecute 中获取 ViewModel
- c++ - 在模板化 Rcpp 函数中调用另一个 cpp 函数
- apache-flink - 使用 Flink SQL 优化 Top-N 查询
- ios - 试图找到自定义标签栏的更好方法
- python - 如何使用python编辑特定目录中XML文件的多个xml标记数据
- next.js - 在 node.js 中使用 next-i18next 翻译
- swift - 如何在可可中转换 NSImageView?
- c# - 图像未从 Xamarin 上传到 php
- vim - 如何在vimscript中关闭终端程序并执行操作
- python - Python读取带有换行符和段落分隔元素的文本文件