我已经覆盖默认编辑器模板(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>
}
}
}
除非我想调整表单(例如更改排序或添加字段集),否则这很有效。我基本上想将上面代码的一部分分成另一个编辑器模板,这导致了Property.ascx。这将通过Html.Editor(“{PropertyName”})或Html.EditorFor(m =&gt; 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>
上述编辑器模板的问题在于它不会为给定类型呈现正确的输入。因此,日期/时间属性将只呈现没有type属性的普通文本框。
我是以正确的方式来做这件事的吗?我应该使用标准的HTML帮助器还是部分视图?如果是这样,我们如何处理通用性质?
答案 0 :(得分:4)
MVC 5.1包含针对这种情况的修复Bootstrap support for editor templates。
您可以通过提供一个非对象作为EditorFor
@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })