您可以稍微调整您的模型以符合您的要求:
public class QuestionSheetViewModel
{
public List<QuestionViewModel> Questions { get; set; }
public int QuestionId { get; set; }
}
public class QuestionViewModel
{
public string QuestionText { get; set; }
public int SelectedAnswerId { get; set; }
public List<AnswerViewModel> Answers { get; set; }
}
public class AnswerViewModel
{
public int AnswerId { get; set; }
public string Text { get; set; }
}
然后有一个控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new QuestionSheetViewModel
{
QuestionId = 1,
Questions = new[]
{
new QuestionViewModel
{
QuestionText = "question 1",
SelectedAnswerId = 2,
Answers = new[]
{
new AnswerViewModel { AnswerId = 1, Text = "answer 1" },
new AnswerViewModel { AnswerId = 2, Text = "answer 2" },
}.ToList()
},
new QuestionViewModel
{
QuestionText = "question 2",
SelectedAnswerId = 3,
Answers = new[]
{
new AnswerViewModel { AnswerId = 3, Text = "answer 3" },
new AnswerViewModel { AnswerId = 4, Text = "answer 4" },
}.ToList()
},
}.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(QuestionSheetViewModel model)
{
// When the form is submitted the model will be properly bound
return View(model);
}
}
带有相应的视图 ( ~/Views/Home/Index.cshtml
):
@model QuestionSheetViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(x => x.QuestionId)
<ul>
@Html.EditorFor(x => x.Questions)
</ul>
<button type="submit">OK</button>
}
以及一个相应的编辑器模板,它将按照惯例为每个问题自动呈现 ( ~/Views/Shared/EditorTemplates/QuestionViewModel.cshtml
):
@model QuestionViewModel
<li>
@Html.DisplayFor(x => x.QuestionText)
@Html.HiddenFor(x => x.QuestionText)
<ul>
@for (int i = 0; i < Model.Answers.Count; i++)
{
<li>
@Html.HiddenFor(x => x.Answers[i].AnswerId)
@Html.HiddenFor(x => x.Answers[i].Text)
@Html.RadioButtonFor(x => x.SelectedAnswerId, Model.Answers[i].AnswerId)
@Html.DisplayFor(x => x.Answers[i].Text)
</li>
}
</ul>
</li>