循环遍历FormCollection以获取单选按钮选择的答案

时间:2014-06-20 03:17:14

标签: c# asp.net-mvc model-view-controller radio-button formcollection

如何使用表单集合获取以[问题] [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
}

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

1 个答案:

答案 0 :(得分:0)

有这个工作

  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 });
   }
 }