我正在尝试提供一个单选按钮列表来从 MVC 3 模型中的一小组字符串中选择一个选项。我正在研究的是调查中问题的编辑器模板。
到目前为止,我遵循了Brad Christie 的建议,这使我能够正确渲染视图。以下是相关代码:
模型 - Question.cs
(注意,这实际上是一个模型优先的 EF 实体,但我认为这并不重要)
public class Question {
// snip unimportant properties
public string QuestionType { get; set; }
}
查看 - Question.cshtml
// snip unimportant view code
<div class="control-group">
@Html.LabelFor(model => model.QuestionType, "Question Type")
<div class="controls">
@Html.EditorFor(model => model.QuestionType, "QuestionType")
@Html.ValidationMessageFor(model => model.QuestionType)
</div>
</div>
查看 - QuestionType.cshtml
@model System.String
@{
var questionTypes = new String[] { "PickOne", "PickMany", "OpenEnded" };
var typesMap = new Dictionary<String, String> {
{ "PickOne", "Pick a single answer" },
{ "PickMany", "Pick several answers" },
{ "OpenEnded", "Open-ended answer" }
};
}
@foreach (var questionType in questionTypes) {
<label class="radio">
@Html.RadioButtonFor(model => model, questionType)
@typesMap[questionType]
</label>
}
尽管该视图创建了正确的 HTML,但当我为调查加载编辑器视图时,在页面加载时未预先选择与其问题类型对应的单选按钮。我假设这与模型绑定有关?
如何根据数据库中存在的选项预先选择正确的单选按钮?如果它很重要,我将使用模型优先实体框架 4 作为我的持久层。