【发布时间】: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