boonjye Ответов: 3

Нужна помощь в проведении онлайн-викторины в asp.net с#


Ребята ,

Я нашел очень находчивую реализацию онлайн-викторины .
Онлайн-Викторина[^]

Но проблема в том, что я хочу повторно использовать этот код и написать его на C# с кодом за формой.

Я пытался конвертировать, но в итоге получил массу ошибок. будет изящно, если кто-нибудь сможет это понять.
Я буду глубоко признателен .

в код позади ,викторины.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;
    }

}


викторины.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 возник из Онлайн-Викторина[^]


<<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>

3 Ответов

Рейтинг:
2

Juggan

публичный частичный класс OnlineTest : System.Web.UI.Page
{
строка strXmlFilePath = HttpContext.Current.Сервер.MapPath("quiz11.xml");
Системы.В формате XML.В XPath.XPathDocument xDoc;
XPathNavigator xNav;

Практическое руководство xNodeIterator;
//Инициализация переменных
инт intTotalQuestion;
int intQuestionNo = 1;
int intScore = 0;

ArrayList arrAnswerHistory = новый ArrayList();

охраняемых недействительными в(объект отправителя, EventArgs в электронной)
{

xdoc по = новой системы.В формате XML.В XPath.XPathDocument(strXmlFilePath);
xNav = xDoc.CreateNavigator();
//Начать новую викторину?

если (!страница.IsPostBack)
{
/- Да! Подсчитайте общий вопрос
intTotalQuestion = xNav.Select("/quiz/mchoice").Рассчитывать;

//Время начала записи
ViewState["StartTime"] = DateTime.Now;

ShowQuestion(intQuestionNo);
}
}

охраняемых недействительными btnSubmit_Click(объект отправителя, EventArgs в электронной)
{

//Извлечение существенных переменных из пакета состояний
intTotalQuestion =преобразовать.ToInt32(ViewState["TotalQuestion"]);
intQuestionNo = конвертировать.ToInt32(ViewState["QuestionNo"]);
intScore = конвертировать.ToInt32(ViewState["Оценка"]);
arrAnswerHistory =(ArrayList) ViewState["AnswerHistory"];
строка x = ViewState["CorrectAnswer"].Метод toString();
//Правильный ответ?
if (rblAnswer.Элемент.Ценность.Равно( x))
{
intScore += 1;
arrAnswerHistory.Add(0);
}
еще
{
аррансверхистория.Добавить(rblAnswer.Элемент.Ценность);
}

//Конец викторины?

if (intQuestionNo == intTotalQuestion)
{
/- Да! Покажите результат...
QuizScreen.Видна = ложь;
ResultScreen.Видимое = истинное;

//Экран результатов рендеринга
ShowResult();


}
еще
{
/- Еще нет! Покажите еще один вопрос...
QuizScreen.Видимое = истинное;
ResultScreen.Видна = ложь;
intQuestionNo += 1;

//Рендеринг следующего вопроса
ShowQuestion(intQuestionNo);
}
}
public void ShowQuestion(int intQuestionNo)
{

строки strXPath = нуль;
int intLoop = 0;
TimeSpan objTimeSpent = значение по умолчанию(TimeSpan);

strXPath = "/quiz/mchoice[" + intQuestionNo.Метод toString() + "]";

//Извлечение вопроса
xNodeIterator = xNav.Select(strXPath + "/вопрос");
xNodeIterator.метод MoveNext();
lblQuestion.Текст = intQuestionNo.ToString() + ". " + xNodeIterator.Текущий.Ценность;

//Извлечение ответов
xNodeIterator = xNav.Select(strXPath + "/ответ");

//Очистить предыдущие списки
rblAnswer.Предметы.Четкий();

intLoop = 0;
while (xNodeIterator.метод MoveNext())
{

intLoop += 1;

//Добавить элемент в список radiobuttonlist
rblAnswer.Предметы.Add(new ListItem(xNodeIterator.Текущий.Ценность, интлуп.Метод toString()));

//Извлечение правильного ответа
строка ans = xNodeIterator.Текущий.GetAttribute("правильно", "");
if (xNodeIterator.Текущий.GetAttribute("правильно", "") == "да")
{
ViewState["CorrectAnswer"] = intLoop;
}

}

//Выходной Общий Вопрос
lblTotalQuestion.Текст = intTotalQuestion.Метод toString();

//Затраченное Время Вывода
objTimeSpent = DateTime.Now.Subtract((DateTime)ViewState["StartTime"]);
lblTimeSpent.Text = objTimeSpent.Минут.ToString() + ":" + objTimeSpent.Секунд.Метод toString();

//Хранить необходимые данные в государственной сумке
ViewState["TotalQuestion"] = intTotalQuestion;
ViewState["оценка"] = intScore;
ViewState["QuestionNo"] = intQuestionNo;
ViewState["AnswerHistory"] = arrAnswerHistory;

}

public void ShowResult()
{
string strResult = null;
int intCompetency = 0;
int intLoop = 0;
строки strXPath = нуль;
TimeSpan objTimeSpent = значение по умолчанию(TimeSpan);

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

strResult = "";
strResult += "результат викторины";
strResult += "Points:" + intScore.ToString() + " of " + intTotalQuestion.Метод toString();
strResult += "ваша компетентность:" + конвертировать.ToInt32(intScore / intTotalQuestion * 100).Метод toString() + "%";
strResult += "затраченное время:" + objTimeSpent.Минут.ToString() + ":" + objTimeSpent.Секунд.Метод toString();
strResult += "";

strResult += "разбивка викторины:";
for (intLoop = 1; intLoop " + intLoop.ToString() + ". " + xNodeIterator.Текущий.Ценность + "";
интервал АЭ=конвертировать.ToInt32(arrAnswerHistory[intLoop - 1]);
если (ae == 0)
{
strResult += "правильно";
}
еще
{
xNodeIterator = xNav.Select(strXPath + "/answer[" + arrAnswerHistory[intLoop - 1].ToString() + "]");
xNodeIterator.метод MoveNext();
strResult += "вы ответили:" + xNodeIterator.Текущий.Ценность + "";
strResult += "неверно";
}
}

lblResult.Text = strResult;
}

}
}


Рейтинг:
0

Juggan

вы можете редактировать свои строки:

строка x = ViewState["CorrectAnswer"].Метод toString();
//Правильный ответ?
if (rblAnswer.Элемент.Ценность.Равно( x))
{
intScore += 1;
arrAnswerHistory.Add(0);
}