循环FormCollection以获取单选按钮SelectedAnswers

本文关键字:单选按钮 SelectedAnswers 获取 FormCollection 循环 | 更新日期: 2023-09-27 18:09:41

如何使用表单集合获得谓词命名为Questions[I]的单选按钮的值?

在表单集合

Questions[0].ObjectId
Questions[0].SelectedAnswer
Questions[1].ObjectId
Questions[1].SelectedAnswer
Questions[2].ObjectId
Questions[2].SelectedAnswer
3 - 13 ... etc...
Questions[14].ObjectId
Questions[14].SelectedAnswer
(a bunch of other stuff)

在控制器

[HttpPost]
public ActionResult PostResults(FormCollection form)
{
    List<SelectedAnswer> selectedAnswers = new List<SelectedAnswer>();
    for (int i = 0; i < 15; i++)
    {
        //this is the part that is not working...
        selectedAnswers.Add(new SelectedAnswer() { questionId = form["Questions"][i].ObjectId; answerId = form["Questions"][i].SelectedAnswer}                
    }
    //continue to do other stuff
}

我的最终目标是将选择的值保存到数据库

循环FormCollection以获取单选按钮SelectedAnswers

成功了

  for (int i = 0; i < 15; i++)
  {
     long x = Int64.Parse(form[String.Format("Questions[{0}].ObjectId", i)]);
     long y = Int64.Parse(form[String.Format("Questions[{0}].SelectedAnswer", i)]);
  if (x > 0 && y > 0)
   {
     selectedAnswers.Add(new SelectedAnswer() { questionId = x, answerId = y });
   }
 }