使用radiobutton的多个问题回答不回复答案值

时间:2014-04-16 18:13:21

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

我有一个表格上面有多个问题,每个表格都有各自的答案,使用单选按钮获取答案。在我的控制器中,当我获得表单集合时,键包含问题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();
    }
}

2 个答案:

答案 0 :(得分:0)

这是解释复杂类型绑定的article,即类

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

答案 1 :(得分:0)

不要使用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})
    }
}