使用EditorFor和Twitter Bootstrap来呈现表单标签,输入和验证消息

And*_*unn 6 asp.net asp.net-mvc mvc-editor-templates twitter-bootstrap

我已经覆盖了默认的编辑器模板(Object.ascx)以生成表单(正文)HTML,该表格遵循Twitter Bootstrap的指南(http://twitter.github.io/bootstrap/base-css.html#forms)执行通过Html.EditorForModel().

@if (ViewData.TemplateInfo.TemplateDepth > 1) 
{
    @(Model == null ? ViewData.ModelMetadata.NullDisplayText : ViewData.ModelMetadata.SimpleDisplayText)
} 
else 
{
    foreach (var property in ViewData.ModelMetadata.Properties.Where(m => m.ShowForEdit @*&& m.ModelType != typeof (System.Data.EntityState)*@ && !m.IsComplexType && !ViewData.TemplateInfo.Visited(m))) 
    {
        if (property.HideSurroundingHtml)
        {
            @Html.Editor(property.PropertyName)
        } 
        else 
        {
            <div class="control-group @(!ViewData.ModelState.IsValidField(property.PropertyName) ? "error" : ViewData.ModelState.ContainsKey(property.PropertyName) ? "success" : "" )">
                @if (!string.IsNullOrEmpty(Html.Label(property.PropertyName).ToHtmlString())) 
                {
                    @Html.Label(property.GetDisplayName() + (property.IsRequired ? " *" : ""), new { @class = "control-label" })
                }

                <div class="controls">
                    @Html.Editor(property.PropertyName)
                    @Html.ValidationMessage(property.PropertyName, "*", new { @class = "help-inline" })
                </div>
            </div>
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

除非我想调整表单(例如更改排序或添加字段集),否则这很有效.我基本上想将上面代码的一部分分成另一个编辑器模板,这导致了Property.ascx.这将通过Html.Editor("{PropertyName"})或Html.EditorFor(m => m.{PropertyName})执行给定属性的标签,输入和验证消息.

<div class="control-group @(!ViewData.ModelState.IsValidField(ViewData.ModelMetadata.PropertyName) ? "error" : ViewData.ModelState.ContainsKey(ViewData.ModelMetadata.PropertyName) ? "success" : "" )">
    @if (!string.IsNullOrEmpty(Html.Label(ViewData.ModelMetadata.PropertyName).ToHtmlString())) 
    {
        @Html.Label(ViewData.ModelMetadata.GetDisplayName() + (ViewData.ModelMetadata.IsRequired ? " *" : ""), new { @class = "control-label" })
    }

    <div class="controls">
        @Html.Editor(ViewData.ModelMetadata.PropertyName)
        @Html.ValidationMessage(ViewData.ModelMetadata.PropertyName, "*", new { @class = "help-inline" })
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

上述编辑器模板的问题在于它不会为给定类型呈现正确的输入.因此,日期/时间属性将只呈现没有type属性的普通文本框.

我是以正确的方式来做这件事的吗?我应该使用标准的HTML帮助器还是部分视图?如果是这样,我们如何处理通用性?

pne*_*ook 4

MVC 5.1 包含针对这种情况的修复,即Bootstrap 对编辑器模板的支持。您可以通过提供匿名对象作为第二个参数来包含标记的其他属性EditorFor

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })
Run Code Online (Sandbox Code Playgroud)