[英]ASP.NET MVC Best way to handle dynamic number of parameters in controller
我有一個考試的視圖模型。 每個考試都有一定數量的問題。 這可能是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)
我正在做的事情感覺有點hacky。 請幫助或讓我知道我在正確的軌道上。 謝謝!
我真的沒有得到整個上下文,但如果這是從表單中的視圖提交,那么表單可能是使用@ 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
}
}
}
使用帶有列表的viewmodel。 唯一需要注意的是綁定到List是一種先進的技術: 模型綁定到List MVC 4
public class Response {
public string QuestionId {get;set;}
public string AnswerId {get;set;}
}
public class ExamViewModel {
public int? TestId {get;set;}
public List<Response> Responses {get;set;}
}
public ActionResult GradeTest(ExamViewModel viewModel)
{
...
我是一個叮咚。 我錯了。 我查找了如何將視圖中的集合傳遞給控制器並解決了問題!
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
我像這樣更新了我的視圖/控制器:
@foreach (var question in Model.TestQuestions)
{
@Html.Hidden("Questions[" + questionIndex.ToString() + "].ID", question.ID)
<h3>@question.Text</h3>
<section>
@foreach (var answer in question.TestAnswers)
{
<div>
@Html.RadioButton("Answers[" + questionIndex.ToString() + "].ID", answer.ID) @answer.Text
</div>
}
</section>
<hr />
questionIndex++;
}
和控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TestDoGrade(int? testID, IEnumerable<TestQuestion> questions, IEnumerable<TestAnswer> answers)
{
您可以接受JObject作為參數。 JObject它會將隱藏的表單數據轉換為可以枚舉的JProperties列表。
JProperty有兩個字段,Name和Value。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.