我有一个考试模型。每次考试都有任意数量的问题。可能是1个问题,也可能是50个问题。提交后,我需要遍历问题并检查答案。我有一个解决方案,但我觉得这不是最佳实践。
int questionNumber = 1;
while (Request.Form["Question" + questionNumber.ToString()] != null)
{
int questionID = Convert.ToInt32(Request.Form["Question" + questionNumber.ToString()]);
int answerID = Convert.ToInt32(Request.Form["Answer" + questionNumber.ToString()]);
//TODO: Check if answer is correct
}
不确定这样做的另一种方式
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GradeTest(int? testID, string[] questionIDs, string[] answerIDs)
我正在做的事情感觉有些古怪。请帮忙,或者让我知道我在正确的轨道上。谢谢!
我确实没有得到整个上下文,但是如果是从表单的视图中提交的,则表单可能是使用@ Html.TextBoxFor或类似的东西构建的。只需将相同的模型用作Post Action的输入即可。请注意,将不包括任何不在表单字段中的属性,如果必须要使用某些属性,请使用HiddenFor。我在下面整理了一个例子。
YourViewModel.cs
public class YourViewModel {
public int ExamID { get; set; }
public string Name { get; set; }
public List<int> QuestionIDs { get; set; }
public List<int> AnswerIDs { get; set; }
}
YourView.cshtml
@model YourViewModel.cs
using(Html.BeginForm("PostExam", "YourController", FormMethod.Post)
{
@Html.HiddenFor(m => m.ExamID)
@Html.AntiForgeryToken()
<strong>Please enter your name</strong>
@Html.TextBoxFor(m => m.Name)
@*Your question and answers goes here*@
<input type="submit" value="Hand in" />
}
YourController.cs
public class YourController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult PostExam(YourViewModel Submitted)
{
//Handle submitted data here
foreach(var QuestionID in Submitted.QuestionIDs)
{
//Do something
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句