你能適應你的模型一點點的滿足您的要求:
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>
謝謝你的完整的答案,這讓很多的感覺!我已經用這種方式實現了這些東西,並且問題的渲染效果很好,但是在提交時,模型完全是空的。它不僅包含問題/答案,還包含「QuestionSheet」對象上的其他字段(我剛剛添加了「UserName」字段作爲示例)。你有什麼想法,爲什麼會這樣?太感謝了。 – user2241047
並通過添加get/set來解決我的視圖模型。再次感謝 – user2241047