【问题标题】:Model binding for a custom EditorTemplate自定义 EditorTemplate 的模型绑定
【发布时间】:2012-05-18 08:29:11
【问题描述】:

我正在尝试提供一个单选按钮列表以从 MVC 3 模型中的一小组字符串中选择一个选项。我正在研究的是调查中问题的编辑器模板。

到目前为止,我已关注Brad Christie's advice,这使我能够正确渲染视图。以下是相关代码:

模型 - 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,但当我为调查加载编辑器视图时,在页面加载时未预先选择与其问题类型对应的单选按钮。我假设这与模型绑定有关?

如何根据数据库中存在的选项预先选择正确的单选按钮?如果它很重要,我将使用模型优先的 Entity Framework 4 作为我的持久层。

【问题讨论】:

  • 查看stackoverflow.com/questions/8357468/…,我相信这与您遇到的问题相同。
  • 从那个答案看来,这种技术不适合编辑器模板。由于我正在制作编辑器模板,因此似乎对我不起作用。有人对这是否正确有任何想法吗?
  • 我认为这个问题意味着您可以使用编辑器模板来满足您的需求,只是不能在编辑器模板中使用 RadioButtonFor。
  • 啊,我一定是看错了。感谢您的信息!

标签: asp.net-mvc asp.net-mvc-3 model-binding mvc-editor-templates


【解决方案1】:

基于RadioButtonFor not selecting value in editor templates

你的模型绑定没问题,就是这个问题

@Html.RadioButtonFor(model => model, questionType)

对应一个空名称,RadioButtonFor 从不检查名称为空的单选按钮。

你应该可以的

@Html.RadioButton("", questionType, questionType == Model)

【讨论】:

  • 这很好用。它比我发现的骇人听闻的方式要干净得多。我想出了一种使用属性字典的方法。它很丑陋,但这要好得多。谢谢!
猜你喜欢
  • 2023-03-19
  • 2011-02-08
  • 1970-01-01
  • 2012-07-31
  • 2019-12-07
  • 1970-01-01
  • 2012-02-18
  • 2011-12-22
  • 2018-05-07
相关资源
最近更新 更多