我有一个实体模型,它包含消息对象的集合,这些消息对象属于 Message 类型,具有多个属性,包括内容、MessageID、from 和 to。
我已经为 Message 类型创建了一个 EditorTemplate,但是,我无法让它显示 Messages 集合的内容。
没有错误,但没有输出。
请注意, View 代码来自父 Talkback 类的 EditorTemplate。您可以让一个 EditorTemplate 为子集合调用另一个 EditorTemplate 吗?
Talkback 和 Message 类都是由 Entity 框架从现有数据库生成的。
查看代码:
<% foreach (TalkbackEntityTest.Message msg in Model.Messages)
{
Html.EditorFor(x=> msg, "Message");
} %>
这是我的模板代码。它是标准的自动生成的 View 代码,有一些小的变化。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TalkbackEntityTest.Message>" %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.MessageID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.MessageID) %>
<%: Html.ValidationMessageFor(model => model.MessageID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.acad_period) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.acad_period) %>
<%: Html.ValidationMessageFor(model => model.acad_period) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.talkback_id) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.talkback_id) %>
<%: Html.ValidationMessageFor(model => model.talkback_id) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.From) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.From) %>
<%: Html.ValidationMessageFor(model => model.From) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.To) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.To) %>
<%: Html.ValidationMessageFor(model => model.To) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.SentDatetime) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.SentDatetime, String.Format("{0:g}", Model.SentDatetime)) %>
<%: Html.ValidationMessageFor(model => model.SentDatetime) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.content) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.content) %>
<%: Html.ValidationMessageFor(model => model.content) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.MessageTypeID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.MessageTypeID) %>
<%: Html.ValidationMessageFor(model => model.MessageTypeID) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
Message 集合中肯定有内容,因为如果我删除 EditorFor 并将 response.write 放在 Message 类的 content 属性上,我会在页面上获得 3 个 Message 对象的内容字段,这与预期完全一样.
最佳答案
您不需要手动foreach
。只需将包含您在 ~/Shared/EditorTemplates/
文件夹中显示的编辑器模板的名为 Message.ascx
的文件放入您的 View 中即可:
<%: Html.EditorFor(model => model.Messages) %>
关于c# - ForEach 与 EditorFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2798700/