【问题标题】:Multiple questions with radiobutton answers not posting back answer value带有单选按钮答案的多个问题未回发答案值
【发布时间】:2014-04-17 02:37:41
【问题描述】:

我有一个表格,上面有多个问题,每个问题都有各自的答案,使用单选按钮作为答案。在我的控制器中,当我获取表单集合时,键包含问题 id 而不是选定的答案 id,我需要答案 id 才能正确更新数据库。

这是我的模型:

public class AccreditationEditModel
{
    public int AccreditationID { get; set; }
    public int UserID { get; set; }
    public DateTime DateCompleted { get; set; }
    public List<QuestionEditModel> Questions { get; set; }
    [Display(Name = "User")]
    public string UserFullName { get; set; }

}

public class AnswerEditModel
{
    public int AnswerID { get; set; }
    public int QuestionID { get; set; }
    public string AnswerText { get; set; }
}

public class QuestionEditModel
{
    public int QuestionID { get; set; }
    public string QuestionText { get; set; }
    public List<AnswerEditModel> Answers { get; set; }
    public int AnswerID { get; set; }
}

观点:

<table>
@foreach (var Question in Model.Questions)
{ 
    <tr>
        <td colspan="2">
            <div>
                <strong>@Question.QuestionText</strong>
            </div>
        </td>
    </tr>
    foreach (var Answer in Question.Answers)
    { 
        <tr>
           <td colspan="2">
                <input style="width:10px" type="radio" id="answer_id_@Answer.AnswerID" name="Question_@Answer.QuestionID" value="@Answer.AnswerID">@Answer.AnswerText
           </td>
        </tr>
    }
}
</table>
<p>
    <input type="submit" value="Save" />
</p>

和我的控制器:

[HttpPost]
public ActionResult Edit(int id, FormCollection model)
{
    try
    {
        id = UserPersistance.UserId(Request);
        Accreditation a = new Accreditation();
        a.LoadByUserID(id);
        a.DateCompleted = DateTime.Now.ToUniversalTime();
        a.Save();       //Get an ID for the accreditation table for new.




        return RedirectToAction("Details");
    }
    catch
    {
        return View();
    }
}

【问题讨论】:

  • 你为什么不用剃刀来创建单选按钮?
  • 我无法按问题对单选按钮进行分组,因此每个问题只能有一个答案。
  • 你可以使用 Razor,并设置 name=Answer.QuestionID 进行分组
  • 这个语法不这样做:@Html.RadioButtonFor(x => Answer.AnswerID, @Answer.QuestionID, new { name=@Answer.QuestionID })

标签: c# .net asp.net-mvc-4 radio-button


【解决方案1】:

不要使用foreach。使用for loop,以便您可以将其直接与您的模型相关联:

for(int i=0; i< model.Questions.Count;i++)
{ 
    model.Question[i].QuestionText

    for(int j=0; j<model.Question[i].Answers.Count; j++)
    { 
        @Html.RadioButtonFor(x => x.Question[i].Answers[j], model.Questions[i].QuestionID, new { @name = model.Questions[i].QuestionID})
    }
}

【讨论】:

    【解决方案2】:

    这里是article,它解释了绑定到复杂类型,即类

    您只需为绑定到 AnswerEditModel.AnswerID 的字段提供正确的名称,例如:name="Answers.AnswerdID"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 2020-02-11
      相关资源
      最近更新 更多