0

我不想使问题过于复杂,但是这里有……我有一个问题和答案文件。我想使用 C# ASP.NET Core MVC 从文件中获取问题,格式为 JSON,使用 AJAX 将问题值返回到网页。通过单击一个按钮来显示问题,该按钮通过使用 Route[] 语句连接到它来运行 C# 方法。然后,同样在同一网页上的 AJAX 中,用户可以提交他们的答案。如果他们是正确的,它会告诉他们。如果不涉及随机数,则此方法有效。随机数只是选择包含问题的文本文件的行 - 这就是它的全部!但是,catch-22 是当用户单击“ANSWER”按钮提交答案时,它会重新运行 C# 方法,该方法会生成一个新的随机数,因此很有可能从文件,

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {  //When document loads, function is ready (this includes ALL of the functions below!)

            $('#showQ').click(function () {
                //Block of code that uses AJAX to DISPLAY questions from Controllers/DemoController.cs/answerQuestion()
                $.ajax(
                    {   //Start of the actual AJAX request code...
                        type: 'GET',    //Use GET method to send values
                        url: '/demo/answerQuestion/',//The location of the method (Controllers/DemoController.cs/answerQuestion)
                        success: function (result) {    //If function is successful, it will display the result
                            $('#displayQ').html(result);  //If the code above is successful, it will display the question inside id="displayQ"
                        }
                    }
                )
            });
            //Block of code that uses AJAX to ANSWER questions from Controllers/DemoController.cs/answerQuestion()
            $('#answerQ').click(function () {   //When answerQ button is clicked, run this function...
                var answer = $('#answer').val();  //var answer = id="answer" field value when answerQ submit button is pressed
                $.ajax(
                    {   //Start of the actual AJAX request code...
                        type: 'GET',    //Use GET method to send values
                        url: '/demo/answerQuestion/' + answer, //Submit answer value to answerQuestion
                        success: function (result) {
                            $('#displayAns').html(result);  //If the code above is successful, it will send the answer and display result in id="displayAns"
                        }
                    }
                )
            });
        }); //End of $(document).ready(function...

    </script>
</head>
<body>

    <fieldset>
        <legend>Question...</legend>
        <br />
        <input type="button" value="Click for question" id="showQ" />
        <br />
        <span id="displayQ"></span>
        <br />
        Answer: <input type="text" id="answer" />
        <br />
        <input type="button" value="Click to submit answer" id="answerQ" />
        <br />
        <span id="displayAns"></span>
        <br />
    </fieldset>

</body>
</html>

从 AJAX 获取值的 C# 方法...

[Route("answerQuestion")]
        [Route("answerQuestion/{answer}")]
        public IActionResult AnswerQuestion(string answer)
        {
            //Need to think of a way to get this to only run when "Next question" button is clicked and not when answer provided!
            //Problem is, if I make it so it only runs if "answer" is not set, then it complains that variable is undefined!
            //It's a bit of a catch-22!!!
            Random rnd = new Random();
            int randomNumber = rnd.Next(0, 10);

            string path = @"C:\Users\aposi\Desktop\csharpweb\HOWMVCWORKS\quizquestions.txt";
            if (System.IO.File.Exists(path))
            {
                string[] allLines = System.IO.File.ReadAllLines(path);
                string randomLine = allLines[randomNumber];
                string removedSlashN = randomLine.Replace("\n", "");
                string removedWhitespace = removedSlashN.Replace(" ", "");
                string[] separatedout = removedWhitespace.Split("|"); //Has to be string array data-type to work with Split() function
                string songname = separatedout[0];
                char songletter = songname[0];
                string artist = separatedout[1];

                if (string.IsNullOrEmpty(answer))
                {
                    return new JsonResult("Artist: " + artist + "First letter of songname: " + songletter);
                }
                else if (answer == songname)
                {
                        return new JsonResult("Well done! You guessed correctly that the song name is: " + songname);
                }
                else if (answer != songname)
                {
                        return new JsonResult("Sorry! You got it wrong! The song name was... " + songname);
                }
                else
                {
                    return new JsonResult("Something went wrong!!!");
                }
            }
            else
            {
                return new JsonResult("No question file found!");
            }
        }
    }
}
4

1 回答 1

0

有几种方法可以解决。

  1. 将其拆分为两个调用:
    • GetQuestion,它返回带有问题的问题的行号,并且
    • AnswerQuestion,它接受行号,这就是您寻找答案的行。
  2. 保持它与您返回问题的行号与问题的一个呼叫。然后将行号与答案一起传回,然后从该行号中提取答案并与他们的答案进行比较。然后你创建一个随机数来寻找一个新问题。
  3. 一个电话保持它,但用问题返回答案。您只需将其保留在您的 JavaScript 中,直到用户回答。然后,您甚至不需要发出新的 AJAX 请求来知道它们是否正确。

我只会在一次调用中保留它,因为使用两个将需要两个请求,并且两次加载文件。

但是要将其保留为一次调用,您需要创建一个类并返回它,而不仅仅是显示的字符串。

public class Question {
    public string Question { get; set; }

    // if you want to send the answer
    public string Answer { get; set; }

    // if you don't want to send the answer
    public int LineNumber { get; set; }

    // text you show in response to their answer. e.g. "Well done! ..."
    public string ResponseText { get; set; }
}

然后您返回该类,并根据发生的情况设置您需要的属性。例如,如果他们回答正确,它看起来像:

return new JsonResult(new Question {
    Question = $"Artist: {artist} First letter of song name: {songletter}",
    Answer = answer, //if you want
    LineNumber = randomNumber,
    ResponseText = $"Well done! You guessed correctly that the song name is: {songname}"
});
于 2019-10-30T23:49:42.700 回答