在asp.net c#中进行在线测验需要帮助 [英] Need help in doing an online quiz in asp.net c#

查看:82
本文介绍了在asp.net c#中进行在线测验需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,



我发现了一个非常足智多谋的在线测验实现。

在线测验 [ ^ ]



但问题是我希望重用此代码并用C#写的代码在表单后面。



我一直试图转换但最终出现了大量错误。如果有人能弄明白的话会很优雅。

我非常感激。



背后的代码,quiz.aspx.cs

Guys ,

I found an very resourceful implementation of online quiz .
Online Quiz[^]

But the problem is i wish to reuse this code and written in C# with code behind form.

I have been trying to convert but end up with ton of error. will be graceful if any one can figure it out.
I be deeply appreciate .

the code behind ,quiz.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;

public partial class _Default : System.Web.UI.Page
{
    //Relative file path to XML data

    string strXmlFilePath = Server.MapPath("quiz.xml");
    XPathDocument xDoc = new XPathDocument(strXmlFilePath);
    XPathNavigator xNav = xDoc.CreateNavigator;

    XPathNodeIterator xNodeIterator;
    //Initialize variables
    int intTotalQuestion;
    int intQuestionNo = 1;
    int intScore = 0;

    ArrayList arrAnswerHistory = new ArrayList();

    public void Page_Load(object sender, EventArgs e)
    {
        //Start a new quiz?

        if (!Page.IsPostBack)
        {
            //Yes! Count total question
            intTotalQuestion = xNav.Select("/quiz/mchoice").Count;

            //Record start time
            ViewState["StartTime"] = DateTime.Now;

            ShowQuestion(intQuestionNo);
        }
    }



    public void btnSubmit_Click(object src, EventArgs e)
    {
        //Retrieve essential variables from state bag
        intTotalQuestion = ViewState["TotalQuestion"];
        intQuestionNo = ViewState["QuestionNo"];
        intScore = ViewState["Score"];
        arrAnswerHistory = ViewState["AnswerHistory"];

        //Correct answer?
        if (rblAnswer.SelectedItem.Value == ViewState["CorrectAnswer"])
        {
            intScore += 1;
            arrAnswerHistory.Add(0);
        }
        else
        {
            arrAnswerHistory.Add(rblAnswer.SelectedItem.Value);
        }

        //End of quiz?

        if (intQuestionNo == intTotalQuestion)
        {
            //Yes! Show the result...
            QuizScreen.Visible = false;
            ResultScreen.Visible = true;

            //Render result screen
            ShowResult();


        }
        else
        {
            //Not yet! Show another question...
            QuizScreen.Visible = true;
            ResultScreen.Visible = false;
            intQuestionNo += 1;

            //Render next question
            ShowQuestion(intQuestionNo);
        }
    }


    public void ShowQuestion(int intQuestionNo)
    {
        string strXPath = null;
        int intLoop = 0;
        TimeSpan objTimeSpent = default(TimeSpan);

        strXPath = "/quiz/mchoice[" + intQuestionNo.ToString() + "]";

        //Extract question
        xNodeIterator = xNav.Select(strXPath + "/question");
        xNodeIterator.MoveNext();
        lblQuestion.Text = intQuestionNo.ToString() + ". " + xNodeIterator.Current.Value;

        //Extract answers
        xNodeIterator = xNav.Select(strXPath + "/answer");

        //Clear previous listitems
        rblAnswer.Items.Clear();

        intLoop = 0;
        while (xNodeIterator.MoveNext())
        {

            intLoop += 1;

            //Add item to radiobuttonlist
            rblAnswer.Items.Add(new ListItem(xNodeIterator.Current.Value, intLoop));

            //Extract correct answer
            if (xNodeIterator.Current.GetAttribute("correct", "") == "yes")
            {
                ViewState["CorrectAnswer"] = intLoop;
            }

        }

        //Output Total Question
        lblTotalQuestion.Text = intTotalQuestion;

        //Output Time Spent
        objTimeSpent = DateTime.Now.Subtract(ViewState["StartTime"]);
        lblTimeSpent.Text = objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();

        //Store essential data to state bag
        ViewState["TotalQuestion"] = intTotalQuestion;
        ViewState["Score"] = intScore;
        ViewState["QuestionNo"] = intQuestionNo;
        ViewState["AnswerHistory"] = arrAnswerHistory;

    }

    public void ShowResult()
    {
        string strResult = null;
        int intCompetency = 0;
        int intLoop = 0;
        string strXPath = null;
        TimeSpan objTimeSpent = default(TimeSpan);

        objTimeSpent = DateTime.Now.Subtract(ViewState["StartTime"]);

        strResult = "<center>";
        strResult += "<h3>Quiz Result</h3>";
        strResult += "<p>Points: " + intScore.ToString() + " of " + intTotalQuestion.ToString();
        strResult += "<p>Your Competency: " + Conversion.Int(intScore / intTotalQuestion * 100).ToString() + "%";
        strResult += "<p>Time Spent: " + objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();
        strResult += "</center>";

        strResult += "<h3>Quiz Breakdown:</h3>";
        for (intLoop = 1; intLoop <= intTotalQuestion; intLoop++)
        {
            strXPath = "/quiz/mchoice[" + intLoop.ToString() + "]";
            xNodeIterator = xNav.Select(strXPath + "/question");
            xNodeIterator.MoveNext();
            strResult += "<b>" + intLoop.ToString() + ". " + xNodeIterator.Current.Value + "</b><br>";
            if (arrAnswerHistory[intLoop - 1] == 0)
            {
                strResult += "<font color=\"green\"><b>Correct</b></font><br><br>";
            }
            else
            {
                xNodeIterator = xNav.Select(strXPath + "/answer[" + arrAnswerHistory[intLoop - 1].ToString() + "]");
                xNodeIterator.MoveNext();
                strResult += "<b>You answered:</b> " + xNodeIterator.Current.Value + "<br>";
                strResult += "<font color=\"red\"><b>Incorrect</b></font><br><br>";
            }
        }

        lblResult.Text = strResult;
    }

}





quiz.aspx。



the quiz.aspx.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Australian Geography Quiz</title>
</head>
<style>
body {
  font-size: 10pt;
  font-family: verdana,helvetica,arial,sans-serif;
  color:#000000;
  background-color:#eeeedd;
}
tr.heading {
  background-color:#900B08;
}
.button {
    border: 1px solid #000000;
    background-color: #ffffff;
}
</style>
<body>
<span id="QuizScreen" runat="server">
<form id="Form2" runat="server">
<table width="100%" border="0" cellpadding="2" cellspacing="0">
  <tr class="heading">
    <td width="50%"><font color="white"><b>Australian Geography Quiz</b></font></td>
    <td width="50%" align="right"><font color="white"><b>www.codeproject.com</b></font></td>
  </tr>
  <tr>
    <td colspan="2">
      <b><asp:label id="lblQuestion" runat="server" /></b><br>
      <asp:radiobuttonlist
         id="rblAnswer"
         RepeatDirection="vertical"
         TextAlign="right"
         RepeatLayout="table"
         runat="server" /><br>
      <asp:requiredfieldvalidator ID="Requiredfieldvalidator1"
         ControlToValidate="rblAnswer"
         ErrorMessage="Please pick an answer!"
         runat="server" /><br>
      <asp:button id="btnSubmit" class="button" text="  Next  " onClick="btnSubmit_Click" runat="server" />
    </td>
  </tr>
  <tr class="heading">
    <td width="50%"><font color="white"><b>Total <asp:label id="lblTotalQuestion" runat="server" /> questions</b></font></td>
    <td width="50%" align="right"><font color="white"><b>Time spent <asp:label id="lblTimeSpent" runat="server" /></b></font></td>
  </tr>
</table>
</form>
</span>
<span id="ResultScreen" runat="server">
<asp:label id="lblResult" runat="server" />
</span>
</body>
</html







quiz.xml来自在线测验 [ ^ ]








the quiz.xml originated from Online Quiz[^]


<<pre lang="xml">?xml version="1.0" encoding="UTF-8"?>
<!-- 10 question quiz about Australian Geography -->
<quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="quiz.xsd">
    <mchoice>
        <question>What is the capital city of Australia?</question>
        <answer>Sydney</answer>
        <answer correct="yes">Canberra</answer>
        <answer>Melbourne</answer>
        <answer>Gold Coast</answer>
    </mchoice>
    <mchoice>
        <question>Launceston is the second largest city in which Australian state?</question>
        <answer>Victoria</answer>
        <answer>New South Wales</answer>
        <answer correct="yes">Tasmania</answer>
        <answer>Western Australia</answer>
    </mchoice>
    <mchoice>
        <question>Which state has the famous 'Twelve Apostles' ?</question>
        <answer correct="yes">Victoria</answer>
        <answer>South Australia</answer>
        <answer>New South Wales</answer>
        <answer>Western Australia</answer>
    </mchoice>
    <mchoice>
        <question>Which is a popular ski resort in NSW?</question>
        <answer correct="yes">Perisher Blue</answer>
        <answer>Mt. Buller</answer>
        <answer>Mt. Baw-Baw</answer>
        <answer>Lake Mountain</answer>
    </mchoice>
    <mchoice>
        <question><![CDATA[Which of the following is <u>NOT</u> Australian native animals?]]></question>
        <answer>Kangaroo</answer>
        <answer correct="yes">Penguin</answer>
        <answer>Koala</answer>
        <answer>Wombat</answer>
    </mchoice>
    <mchoice>
        <question>Which city has an extensive tram network?</question>
        <answer>Sydney</answer>
        <answer correct="yes">Melbourne</answer>
        <answer>Adelaide</answer>
        <answer>Ballarat</answer>
    </mchoice>
    <mchoice>
        <question>What is known as 'The Silver City' in Australia?</question>
        <answer>Alice Springs</answer>
        <answer correct="yes">Broken Hill</answer>
        <answer>Ballarat</answer>
        <answer>Silverton</answer>
    </mchoice>
    <mchoice>
        <question>In which location the war movie 'Thin Red Line' was taken?</question>
        <answer>Anglesea</answer>
        <answer>Apollo Bay</answer>
        <answer>Margaret River</answer>
        <answer>Monkey Mia</answer>
        <answer correct="yes">Townsville</answer>
    </mchoice>
    <mchoice>
        <question><![CDATA[Which is <u>NOT</u> true about Uluru ?]]></question>
        <answer>It is the world biggest monolith located in the centre of Australian continent</answer>
        <answer>It was named 'Ayers Rock' by European explorer William Gosse in 1873</answer>
        <answer correct="yes">Aboriginal people encourage tourists to climb Uluru</answer>
        <answer>The area contains carvings and paintings by Aboriginal people</answer>
    </mchoice>
    <mchoice>
        <question>What is so special about Longreach?</question>
        <answer>The place where a blacksmith named Thomas Hiscock found the first gold that triggerred gold rush</answer>
        <answer>The town has an expansive, well-preserved penal colony of Australia's early history</answer>
        <answer correct="yes">The first commercial flight by Qantas took from this town in 1921</answer>
        <answer>None of these answers are correct</answer>
    </mchoice>
</quiz>

推荐答案

查看此链接



http://www.c-sharpcorner.com/UploadFile/amitware/AQuizApplicationusingWindowsForm11272005233330PM/AQuizApplicationusingWindowsForm。 aspx [ ^ ]


你可以编辑你的行:



string x = ViewState [CorrectAnswer]。ToString();

//正确回答?

if(rblAnswer.SelectedItem.Value.Equals(x))

{

intScore + = 1;

arrAnswerHistory.Add(0);

}
you may edit your lines:

string x = ViewState["CorrectAnswer"].ToString();
//Correct answer?
if (rblAnswer.SelectedItem.Value.Equals( x))
{
intScore += 1;
arrAnswerHistory.Add(0);
}


pub lic partial class OnlineTest:System.Web.UI.Page

{

string strXmlFilePath = HttpContext.Current.Server.MapPath(quiz11.xml);

System.Xml.XPath.XPathDocument xDoc;

XPathNavigator xNav;



XPathNodeIterator xNodeIterator;

//初始化变量

int intTotalQuestion;

int intQuestionNo = 1;

int intScore = 0;



ArrayList arrAnswerHistory = new ArrayList();



protected void Page_Load(object sender,EventArgs e)

{



xDoc = new System.Xml.XPath.XPathDocument(strXmlFilePath);

xNav = xDoc.CreateNavigator();

//开始新的测验?



if(!Page.IsPostBack)

{

//是的!总计问题

intTotalQuestion = xNav.Select(/ quiz / mchoice)。计数;



//记录开始时间

ViewState [StartTime] = DateTime.Now;



ShowQuestion(intQuestionNo);

}

}



protected void btnSubmit_Click(object sender,EventArgs e)

{



//从状态包中检索基本变量

intTotalQuestion = Convert.ToInt32(ViewState [TotalQuestion]);

intQuestionNo = Convert.ToInt32 (ViewState [QuestionNo]);

intScore = Convert.ToInt32(ViewState [Score]);

arrAnswerHistory =(ArrayList)ViewState [AnswerHistory] ;

string x = ViewState [CorrectAnswer]。ToString();

//正确答案?

if(rblAnswer.SelectedItem.Value.Equals(x))

{

intScore + = 1;

arrAnswerHistory.Add (0);

}

其他

{

arrAnswerHistory.Add(rblAnswer.SelectedItem.Value);

}



//测验结束?



if(intQuestionNo == intTotalQuestion)

{

//是的!显示结果...

QuizScreen.Visible = false;

ResultScreen.Visible = true;



//渲染结果画面

ShowResult();





}

否则

{

//还没有!显示另一个问题...

QuizScreen.Visible = true;

ResultScreen.Visible = false;

intQuestionNo + = 1;



//渲染下一个问题

ShowQuestion(intQuestionNo);

}

}

public void ShowQuestion(int intQuestionNo)

{



string strXPath = null;

int intLoop = 0;

TimeSpan objTimeSpent = default(TimeSpan);



strXPath =/ quiz / mchoice [+ intQuestionNo .ToString()+];



//提取问题

xNodeIterator = xNav.Select(strXPath +/ question) ;

xNodeIterator.MoveNext();

lblQuestion.Text = intQuestionNo.ToString()+。+ xNodeIterator.Current.Value;



//提取答案

xNodeIterator = xNav.Select(strXPath +/ answer);



/ /清除以前的listitems

rblAnswer.Items.Clear();



intLoop = 0;

while( xNodeIterator.MoveNext())

{



intLoop + = 1;



//将项目添加到radiobuttonlist

rblAnswer.Items.Add(new ListItem(xNodeIterator.Current.Value,intLoop.ToString()));



//提取正确答案

string ans = xNodeIterator.Current.GetAttribute(correct,);

if(xNodeIterator.Current.GetAttribute (正确,)==是)

{

ViewState [CorrectAnswer] = intLoop;

}



}



//输出总问题
lblTotalQuestion.Text = intTotalQuestion.ToString();



//输出时间花费

objTimeSpent = DateTime.Now。减去((DateTime)ViewState [StartTime]);

lblTimeSpent.Text = objTimeSpent.Minutes.ToString()+:+ objTimeSpent.Seconds.ToString();



//将基本数据存储到州包中

ViewState [TotalQuestion] = intTotalQuestion;

ViewState [Score] = intScore;

ViewState [QuestionNo] = intQuestionNo;

ViewState [AnswerHistory] = arrAnswerHistory;



}



public void ShowResult()

{

string strResult = null;

int intCompetency = 0;

int intLoop = 0;

string strXPath = null;

TimeSpan objTimeSpent = default(TimeSpan);



objTimeSpent = DateTime.Now.Subtract((DateTime)ViewState [StartTime]);



strResult =;

strResult + =测验结果;

strResult + =点数:+ intScore.ToString()+of+ intTotalQuestion.ToString();

strResult + =你的能力:+ Convert.ToInt32(intScore / intTotalQuestion * 100).ToString()+%;

strResult + =花费的时间:+ objTimeSpent .Minutes.ToString()+:+ objTimeSpent.Seconds.ToString();

strResult + =;



strResult + =测验分解:;

for(intLoop = 1; intLoop+ intLoop.ToString()+。 + xNodeIterator.Current.Value +;

int ae = Convert.ToInt32(arrAnswerHistory [intLoop - 1]);

if(ae == 0)

{

strResult + =正确;

}

其他

{

xNodeIterator = xNav.Select(strXPath +/ answer [+ arrAnswerHistory [intLoop - 1] .ToString()+]);

xNodeIterator.MoveNext( );

strResult + =你回答:+ xNodeIterator.Current.Value +;

strResult + =不正确;

}

}



lblResult.Text = strResult;

}



}

}
public partial class OnlineTest : System.Web.UI.Page
{
string strXmlFilePath = HttpContext.Current.Server.MapPath("quiz11.xml");
System.Xml.XPath.XPathDocument xDoc;
XPathNavigator xNav;

XPathNodeIterator xNodeIterator;
//Initialize variables
int intTotalQuestion;
int intQuestionNo = 1;
int intScore = 0;

ArrayList arrAnswerHistory = new ArrayList();

protected void Page_Load(object sender, EventArgs e)
{

xDoc = new System.Xml.XPath.XPathDocument(strXmlFilePath);
xNav = xDoc.CreateNavigator();
//Start a new quiz?

if (!Page.IsPostBack)
{
//Yes! Count total question
intTotalQuestion = xNav.Select("/quiz/mchoice").Count;

//Record start time
ViewState["StartTime"] = DateTime.Now;

ShowQuestion(intQuestionNo);
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{

//Retrieve essential variables from state bag
intTotalQuestion =Convert.ToInt32(ViewState["TotalQuestion"]);
intQuestionNo = Convert.ToInt32(ViewState["QuestionNo"]);
intScore = Convert.ToInt32(ViewState["Score"]);
arrAnswerHistory =(ArrayList) ViewState["AnswerHistory"];
string x = ViewState["CorrectAnswer"].ToString();
//Correct answer?
if (rblAnswer.SelectedItem.Value.Equals( x))
{
intScore += 1;
arrAnswerHistory.Add(0);
}
else
{
arrAnswerHistory.Add(rblAnswer.SelectedItem.Value);
}

//End of quiz?

if (intQuestionNo == intTotalQuestion)
{
//Yes! Show the result...
QuizScreen.Visible = false;
ResultScreen.Visible = true;

//Render result screen
ShowResult();


}
else
{
//Not yet! Show another question...
QuizScreen.Visible = true;
ResultScreen.Visible = false;
intQuestionNo += 1;

//Render next question
ShowQuestion(intQuestionNo);
}
}
public void ShowQuestion(int intQuestionNo)
{

string strXPath = null;
int intLoop = 0;
TimeSpan objTimeSpent = default(TimeSpan);

strXPath = "/quiz/mchoice[" + intQuestionNo.ToString() + "]";

//Extract question
xNodeIterator = xNav.Select(strXPath + "/question");
xNodeIterator.MoveNext();
lblQuestion.Text = intQuestionNo.ToString() + ". " + xNodeIterator.Current.Value;

//Extract answers
xNodeIterator = xNav.Select(strXPath + "/answer");

//Clear previous listitems
rblAnswer.Items.Clear();

intLoop = 0;
while (xNodeIterator.MoveNext())
{

intLoop += 1;

//Add item to radiobuttonlist
rblAnswer.Items.Add(new ListItem(xNodeIterator.Current.Value, intLoop.ToString()));

//Extract correct answer
string ans = xNodeIterator.Current.GetAttribute("correct", "");
if (xNodeIterator.Current.GetAttribute("correct", "") == "yes")
{
ViewState["CorrectAnswer"] = intLoop;
}

}

//Output Total Question
lblTotalQuestion.Text = intTotalQuestion.ToString();

//Output Time Spent
objTimeSpent = DateTime.Now.Subtract((DateTime)ViewState["StartTime"]);
lblTimeSpent.Text = objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();

//Store essential data to state bag
ViewState["TotalQuestion"] = intTotalQuestion;
ViewState["Score"] = intScore;
ViewState["QuestionNo"] = intQuestionNo;
ViewState["AnswerHistory"] = arrAnswerHistory;

}

public void ShowResult()
{
string strResult = null;
int intCompetency = 0;
int intLoop = 0;
string strXPath = null;
TimeSpan objTimeSpent = default(TimeSpan);

objTimeSpent = DateTime.Now.Subtract((DateTime)ViewState["StartTime"]);

strResult = "";
strResult += "Quiz Result";
strResult += "Points: " + intScore.ToString() + " of " + intTotalQuestion.ToString();
strResult += "Your Competency: " + Convert.ToInt32(intScore / intTotalQuestion * 100).ToString() + "%";
strResult += "Time Spent: " + objTimeSpent.Minutes.ToString() + ":" + objTimeSpent.Seconds.ToString();
strResult += "";

strResult += "Quiz Breakdown:";
for (intLoop = 1; intLoop " + intLoop.ToString() + ". " + xNodeIterator.Current.Value + "";
int ae=Convert.ToInt32(arrAnswerHistory[intLoop - 1]);
if (ae == 0)
{
strResult += "Correct";
}
else
{
xNodeIterator = xNav.Select(strXPath + "/answer[" + arrAnswerHistory[intLoop - 1].ToString() + "]");
xNodeIterator.MoveNext();
strResult += "You answered: " + xNodeIterator.Current.Value + "";
strResult += "Incorrect";
}
}

lblResult.Text = strResult;
}

}
}


这篇关于在asp.net c#中进行在线测验需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆