如何保持得分?

时间:2013-03-05 18:12:15

标签: c#

我正在进行迷你测试,我不确定如何制作一个在用户提交测试后更新当前分数的运行分数。分数可以波动25分,具体取决于问题是从错误到正确,反之亦然。

public partial class _Default : System.Web.UI.Page
{
private int totalScore = 0;

public void IncrementScore()
{
    totalScore += 25;
}

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        lblHeader.Text = "quiz not taken";
    }
    else
    {
        lblHeader.Text = "Score: " + totalScore;
    }
}

protected void Submit_Click(object sender, EventArgs e)
{

    /***************************************************************************/
    if (IsValid)
        if (txtAnswer.Text.Equals("primary", StringComparison.InvariantCultureIgnoreCase))
        {
            lblQuestionResult1.ForeColor = System.Drawing.Color.Green;
            lblQuestionResult1.Text = "Correct";
        }
        else
        {
            lblQuestionResult1.ForeColor = System.Drawing.Color.Red;
            lblQuestionResult1.Text = "Incorrect";
        }

    /***************************************************************************/
    if (ddList.SelectedItem.Text.Equals("M:N"))
    {
        lblQuestionResult2.ForeColor = System.Drawing.Color.Green;
        lblQuestionResult2.Text = "Correct";
    }
    else
    {
        lblQuestionResult2.ForeColor = System.Drawing.Color.Red;
        lblQuestionResult2.Text = "Incorrect";
    }

    /***************************************************************************/
    if (RadioButton4.Checked == true)
    {
        lblQuestionResult3.ForeColor = System.Drawing.Color.Green;
        lblQuestionResult3.Text = "Correct";
    }
    else
    {
        lblQuestionResult3.ForeColor = System.Drawing.Color.Red;
        lblQuestionResult3.Text = "Incorrect";
    }

    /***************************************************************************/
    lblQuestionResult4.ForeColor = System.Drawing.Color.Red;
    lblQuestionResult4.Text = "Incorrect";
    if (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked)
    {
        lblQuestionResult4.ForeColor = System.Drawing.Color.Green;
        lblQuestionResult4.Text = "Correct";
    }
}
}

2 个答案:

答案 0 :(得分:2)

递增的方法

private int totalScore = 0;

将无效,因为您为每个HTTP请求获得了_Default的新实例。

您可以将自己的得分保持在Session

但是,我建议总是在需要时通过循环搜索答案并根据需要与每个答案相关联得分来重新计算总分。如果人们回去并改变答案(假设允许这样做),这简化了逻辑。

答案 1 :(得分:0)

将其修改为类似于查看,检查语法,未使用VS

protected void Page_Load(object sender,EventArgs e) {

if (!IsPostBack)
{
    lblHeader.Text = "quiz not taken";
}
else
{
    Session["TotalScore"] = ""+totalScore; //Storing it in a session
    lblHeader.Text = "Score: " + Session["TotalScore"];
}

}

//增量方法

if(Session["TotalScore"]!=null)
 { 
  totalScore += 25;
 } 
else
{
totalScore=int.Parse(Session["TotalScore"])+25;
}