我是MVC的新手。我正在尝试使用单选按钮来呈现选项问题。 这是我尝试过的。我可以使用单选按钮显示选项问题,但我只能在问题中选择一个单选按钮。
型号:
public class CheckListModel()
{
IEnumerable<QuestionModel> Questions { get; set; }
}
Public class QuestionModel()
{
Int Id { get; set; }
string Question { get; set; }
IEnumerable<AnswerModel> Answers { get; set; }
}
Public class AnswerModel()
{
Int Id { get; set; }
string Answer { get; set; }
}
查看:
@if (Model != null)
{
if (Model.CheckListModel != null)
{
int i = 0;
<div class="form-group">
<fieldset>
@foreach (var question in Model.CheckListModel.Questions)
{
<legend>@question.Question</legend>
foreach (var answer in question.Answers)
{
i++;
string nameAtt = "Grp" + i.ToString();
<div class="radio">
@Html.RadioButtonFor(a => a.eCheckListModel.Questions.Where( q => q.Id ==
question.Id).FirstOrDefault().Answers.Where(b => b.Id == answer.Id).FirstOrDefault
().Answer, answer.Id.ToString(), new { @name = nameAtt, @id = nameAtt })
@answer.Answer
</div>
}
}
</fieldset>
</div>
}
}
答案 0 :(得分:7)
您的方法无法正常工作,因为每个单选按钮的name属性未被正确删除。使用... new { @name = nameAtt,..
毫无意义,因为Html Helpers会覆盖任何设置name属性的尝试。
首先,在控制器中填充您的视图模型(使用与该问题相关的答案填充每个问题),并向QuestionModel
添加一个允许您绑定所选答案的属性。
模型
public class CheckListModel
{
public List<QuestionModel> Questions { get; set; } // use List (easier for indexing the name attribute
... // other properties of model
}
public class QuestionModel
{
public int Id { get; set; }
public string Question { get; set; }
public int SelectedAnswer { get; set; } // Add this
public List<AnswerModel> Answers { get; set; }
}
public class AnswerModel
{
public int ID { get; set; }
public string Answer { get; set; }
}
查看
@model YourAssembly.CheckListModel
@using (Html.BeginForm())
{
....
for (int i = 0; i < Model.Questions.Count; i++)
{
@Html.HiddenFor(m => m.Questions[i].ID) // for postback
<p>@Model.Questions[i].Question</p>
for (int j = 0; j < Model.Questions[i].Answers.Count; j++)
{
<div>
@Html.RadioButtonFor(m => m.Questions[i].SelectedAnswer, Model.Questions[i].Answers[j].ID)
<span>@Model.Questions[i].Answers[j].Answer</span>
</div>
}
}
....
}
这将呈现输入<input type="hidden" name="Questions[0].ID"..
,<input type="radio" name="Questions[0].SelectedAnswer"..
等