2012-05-31 51 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

相关问题