Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC 在 Controller 中处理动态参数数量的最佳方式

2024年08月06日31mfrbuaa

我有一个用于考试的 View 模型。每个考试都有任意数量的问题。可以是 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) 

我正在做的事情感觉有点老套。请帮助或让我知道我在正确的轨道上。谢谢!

请您参考如下方法:

我真的不了解整个上下文,但如果这是从表单中的 View 提交的,那么表单可能是使用 @Html.TextBoxFor 或类似的东西构建的。只需将相同的模型作为后操作的输入即可。请注意,任何不在表单字段中的属性都不会被包括在内,如果您必须拥有某些东西,请使用 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 
        } 
    } 
}