where to store temporary data in MVC 2.0 project
I'm starting to learn MVC 2.0 and I'm trying to create a site with a quiz: user is asked a question and given several options of answer. If he chooses the right answer he gets some points, if he doesn't, he looses them.
I tried to do this the following way
public class HomeController : Controller
{
private ITaskGenerator taskGenerator = new TaskGenerator();
private string correctAnswer;
public ActionResult Index()
{
var task = taskGenerator .GenerateTask();
ViewData["Task"] = task.Task;
ViewData["Options"] = task.Options;
correctAnswer= task.CorrectAnswer;
return View();
}
public ActionResult Answer(string id)
{
if (id == correctAnswer)
return View("Correct")
return View("Incorrect");
}
}
But I have a problem: when user answers the cotroller class is recreat开发者_如何学Ced and I loose correct answer. So what is the best place to store correct answer? Should I create a static class for this purpose?
Thanks for your help!There are many different ways to persist data across multiple requests.
- Cookies
- Database layer
- View state (render the data down and pass it back up in each request)
to name a few. The simplest of these is probably a view state implementation. You can roll your own like this
<input type="hidden" name="question_1" value="<%=ViewData["question_1"]%>" />
This input will get reposted in the next submission, so you can keep track of the value.
public ActionResult Step1Post(string answer)
{
ViewData["question_1"] = answer;
return View("Step2")
}
public ActionResult Step2Post(string answer, string question_1)
{
question_1; // the answer from step 1
answer; // the answer from step 2
}
you could also store it in session with a unique key guid and store only the sessionKey in the view as a hidden input
actually it might also depend on the amount of data you will store
It sounds like taskGenerator.GenerateTask() will give you some type of a task, but is that Task persisted anywhere? (Where does this method get the task from)?
If there is an ID associated with the Task, you can send the taskId down in your view and then look the task up again, when they answer. You can then grab the CorrectAnswer from that task and do your comparison.
精彩评论