EditorForModel - 使用editorfor时复制标签

时间:2012-08-16 17:24:10

标签: asp.net-mvc mvc-editor-templates editortemplates

我在ASP.NET MVC应用程序中为不同的数据类型(字符串,DateTime等)使用了许多编辑器模板。例如,以下是我用于字符串的内容:

<div class="editor-label">
     @Html.Label("")
</div>
<div class="editor-field">
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text", placeholder = ViewData.ModelMetadata.Watermark })
    @Html.ValidationMessage("")
</div>

我想在我的视图中使用EditorForModel,但是当我这样做时,似乎为每个属性添加了它自己的标签,导致重复的标签(因为我的字符串编辑器模板中有一个标签)。有什么办法,除了从我的字符串editortemplate(在这个例子中)中删除标签,我可以告诉editorformodel不要插入标签吗?

1 个答案:

答案 0 :(得分:8)

一种可能是覆盖default object editor template~/Views/Shared/EditorTemplates/Object.cshtml)并删除它添加的标签:

@if (ViewData.TemplateInfo.TemplateDepth > 1) 
{
    @ViewData.ModelMetadata.SimpleDisplayText
}
else 
{
    foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm))) 
    {
        if (prop.HideSurroundingHtml) 
        {
            @Html.Editor(prop.PropertyName)
        }
        else 
        {
            <div class="editor-field">
                @Html.Editor(prop.PropertyName)
                @Html.ValidationMessage(prop.PropertyName)
            </div>
        }
    }    
}