6

我已經重寫默認編輯器模板(Object.ascx)來生成表單(body)HTML,它遵循Twitter Bootstrap的指導方針(http://twitter.github.io/bootstrap/base-css.html#forms)執行通過Html.EditorForModel()。使用EditorFor和Twitter Bootstrap來渲染表單標籤,輸入和驗證消息

@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 => 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助手還是部分視圖?如果是這樣,我們如何處理通用性?

回答

4

MVC 5.1包含一個針對這種情況的修復程序,Bootstrap support for editor templates。 可以通過提供一個anonmyous對象作爲第二個參數EditorFor

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, }) 
+0

如何ü可以創建一個融合了htmlAttributes一個templateeditor包括爲標記的附加屬性? –

相關問題