我想使用radiobuttonfor和checkboxFor进行单个或多个答案测验,但我无法使其工作。我看到的所有示例的问题是,问题模型还注册了SelectedAnswer,但在我的情况下,我希望每个可能的答案都是可选的,因为一些问题会有多个答案,因此isSelected属性直接在Answer模型中。
因此,对于单个答案的问题,当我尝试使用RadioButtonFor(m => m [问题] .Answers [answerToDisplayId] .IsSelected)创建我的模型时,每个答案都在其自己的组中,并且在未选中时不会取消选中我从那个问题中检查了另一个答案(基本上它的行为就像一个checkBoxFor)
我目前拥有的:问题模型
public enum questionfield
{
Chaser, Beater, Seeker, Contact, Process, Other
};
public enum QuestionDifficulty
{
Basic, Advanced
};
public enum AnswerType
{
SingleAnswer, MultipleAnswer
}
public class Question
{
public int Id { get; set; }
[Required(ErrorMessage = "Question name not valid")]
public string Name { get; set; }
[Required]
public QuestionField Field { get; set; }
[Required]
public QuestionDifficulty Difficulty { get; set; }
[Required]
public bool IsVideo { get; set; }
public string VideoURL { get; set; }
[Required]
public string QuestionText { get; set; }
[Required]
public AnswerType AnswerType { get; set; }
[Required]
public List<Answer> Answers { get; set; }
[Required]
public String AnswerExplanation { get; set; }
答案模型:
public class Answer
{
public int Id { get; set; }
public String Answertext { get; set; }
public Boolean IsTrue { get; set; }
public Boolean IsSelected { get; set; }
}
观点:
<div>
<!-- For each Question, display a new div with the Title, the question code, the question text, the video if there is one, then the possible answers depending on the type of answers-->
@using(Html.BeginForm("QuizzResult", "Home"))
{
for(int i = 0; i < Model.Count; i++)
{
<div class="QuizzQuestion">
<div class="QuizzQuestionTitle">@Model[i].Id : @Model[i].Name</div> @Html.HiddenFor(m => Model[i].Id)
<div class="QuizzQuestiontext">@Model[i].QuestionText</div>
@if(@Model[i].IsVideo)
{
<div class="QuizzQuestionVideoContainer">
<iframe class="QuizzQuestionVideo" id="ytplayer" type="text/html"
src="@Model[i].VideoURL"
frameborder="0"></iframe>
</div>
}
<div class="RadioButtonAnswers">
@if (@Model[i].AnswerType == QRefTrain3.Models.AnswerType.SingleAnswer)
{
for (int j = 0; j < Model[i].Answers.Count; j++)
{
@Model[i].Answers[j].Answertext @Html.RadioButtonFor(m => m[i].Answers[j].IsSelected, true)
@Html.HiddenFor(m => Model[i].Answers[j].IsTrue)
}
}
</div>
</div>
}
<input type="submit" value="Validate Answers"/>
}
</div>
控制器:
[HttpPost]
public ActionResult QuizzResult(List<Question> answers)
{
foreach(Question a in answers)
{
var b = Request.Form[a.Id.ToString()];
}
Result result = new Result();
foreach (Question q in answers)
{
result.QuestionsAskedIds.Add(q.Id);
if (Question.IsGoodAnswer(q))
{
result.GoodAnswersIds.Add(q.Id);
}
}
if (User.Identity.IsAuthenticated)
{
result.User = Dal.Instance.GetUserByName(HttpContext.User.Identity.Name);
Dal.Instance.CreateResult(result);
}
return View("QuizResult", result);
}
这样做的好方法是什么?谢谢!
答案 0 :(得分:0)
如果有人会看到这个:
我找到的解决方案是更改模型:不是每个答案都有一个IsSelected参数,而是将一个List selectedAnswers添加到Question模型中。然后,在视图中,添加您的radiobutton,如下所示:
key
您将在SelectedAnswers列表中存储此问题的每个所选答案的ID。然后,您可以使用此数据创建结果。