【发布时间】:2012-09-10 16:11:15
【问题描述】:
我刚刚把自己弄得一团糟,我很难想出自己的想法。我有以下域模型(为简洁起见减少了):
public class Questionnaire
{
public int Id { get; set; }
public IList<QuestionGroup> QuestionGroups { get; set; }
}
public class QuestionGroup
{
public int Id { get; set; }
public string Name { get; set; }
public int Order { get; set; }
public IList<Question> Questions { get; set; }
}
public class Question
{
public int Id { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public string Headings { get; set; }
public IList<Answer> Answers { get; set; }
}
public class Answer
{
public int Id { get; set; }
public string Text { get; set; }
}
现在,当我在我的视图中渲染我的Questionnaire 时,我正在为每个QuestionGroup 和Question 使用EditorTemplates。在渲染我的Question 时,我正在查看Type 属性(类似于RadioButtonList 或TextArea)和每个Heading(这是一个逗号分隔的字符串)。例如,假设我们有一个 Question 像这样初始化:
var question = new Question() {
Text = "My Question Text",
Type = "RadioButtonList",
Headings = "Very Difficult,2,3,4,Very Easy"
};
然后我们会这样结束:
在我的 EditorTemplate 中生成如下:
@foreach (var heading in Model.Headings.Split(','))
{
<li>
<div>
<strong>@heading</strong>
@Html.RadioButton(Model.Id.ToString(), heading)
</div>
</li>
}
这个标记看起来像这样:
<ul>
<li>
<div>
<strong>Very Difficult</strong>
<input id="group_question_1" name="group.question.1" type="radio" value="Very Difficult" />
</div>
</li>
<li>
<div>
<strong>2</strong>
<input id="group_question_1" name="group.question.1" type="radio" value="2" />
</div>
</li>
<li>
<div>
<strong>3</strong>
<input id="group_question_1" name="group.question.1" type="radio" value="3" />
</div>
</li>
<li>
<div>
<strong>4</strong>
<input id="group_question_1" name="group.question.1" type="radio" value="4" />
</div>
</li>
<li>
<div>
<strong>Very Easy</strong>
<input id="group_question_1" name="group.question.1" type="radio" value="Very Easy" />
</div>
</li>
</ul>
我制作了一个自定义模型绑定器,但这就是我有点卡住的地方。我的实际问题是:
- 如何根据我的领域模型在视图中保留选定的值?
- 对于这样的事情,我是否使用了正确的方法,或者我是否有路要走?li>
我必须承认,我还处于 MVC 的学习阶段,所以我可能对自己的尝试有些盲目。任何帮助总是很感激!
【问题讨论】:
-
不要混淆用于显示视图的模型和用于获取结果的模型——这些可以(并且可能应该是不同的)。请参阅 Dino Esposito 的 The Three Models of ASP.NET MVC Apps。
-
@Oded:有趣的是,我确实考虑过使用视图模型作为代理,但试图通过让我的表示层直接与域模型一起工作来保持我的代码最小化——我同意这是一个例外而不是不是规则,但到目前为止它对我有用。
标签: c# asp.net-mvc model-binding