2012-05-31 63 views
3

我在MVC模型中的以下屬性:生成HTML的MVC 3自動屬性根據數據類型

[Range(0, double.MaxValue, ErrorMessage = "The Volume must have positive values!")]  
public decimal? Volume { get; set; } 

生成的HTML是

<input type="text" value="1,00" name="Product.Volume" id="Product_Volume" data-val-range-min="0" data-val-range-max="1.79769313486232E+308" data-val-range="The Volume must have positive values!" data-val-number="The field Volume must be a number." data-val="true" class="text-box single-line"> 

如何使生成的HTML是是這樣的:

<input type="text" value="1,00" name="Product.Volume" id="Product_Volume" data-val-range-min="0" data-val-range-max="1.79769313486232E+308" data-val-range="The Volume must have positive values!" data-val-number="The field Volume must be a number." data-val="true" class="text-box single-line" data-type="decimal" > 

不同的是額外的data-type="decimal"

我想要添加HTML屬性自動,所以我不必手動添加它。

回答

0

我的解決辦法是HTML TextBoxFor輔助方法的重寫:

 public static MvcHtmlString TextBoxWithCustomHtmlAttributesFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) 
     { 
      Type propertyType = typeof(TProperty); 
      Type undelyingNullableType = Nullable.GetUnderlyingType(propertyType); 
      var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); 
      string prefix = ExpressionHelper.GetExpressionText(expression); 
      var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix, metadata); 

      string pType = (undelyingNullableType ?? propertyType).Name.ToString().ToLower(); 
      if (htmlAttributes != null) 
      { 
       var dataTypeDict = new Dictionary<string, object>(); 
       dataTypeDict.Add("data-type", pType); 
       if (validationAttributes != null && validationAttributes.Count > 0) 
       { 
        foreach (var i in validationAttributes) 
        { 
         dataTypeDict.Add(i.Key, i.Value); 
        } 
       } 
       htmlAttributes = Combine(new RouteValueDictionary(htmlAttributes), new RouteValueDictionary(dataTypeDict)); 
      } 
      var textBox = helper.TextBoxFor(expression, (Dictionary<string, object>)htmlAttributes); 
      return textBox; 
     } 
10

創建自己的顯示模板,爲Decimal型編輯器模板的意見,這樣你可以控制它的顯示,然後任何Model屬性是Decimal型的,只要你撥打Html.DisplayFor(m => m.DecimalType)Html.EditorFor(m => m.DecimalType)

會自動使用該視圖

在文件夾中添加這些意見意見>共享> DisplayTemplates和EditorTemplates

例如,您EditorTemplate會是這樣:

@model decimal 
@{ 
    Layout = "~/Views/Shared/EditorTemplates/Template.cshtml"; 
} 

@Html.TextBoxFor(x => x, new {data-type = "decimal"}) 
+0

謝謝您的回答。我是否必須在各處創建搜索/替換? 另外,我想手動放置數據註釋會發生什麼? –

+0

@DragosDurlut沒有問題,不需要在任何地方搜索/替換,因爲您的模型會自動爲給定類型「decimal」選取模板。您的其他數據註釋應保持不變 – mattytommo

相關問題