根据数据类型在MVC 3中自动生成HTML属性

时间:2012-05-31 09:09:52

标签: c# .net asp.net-mvc asp.net-mvc-3 razor

我在MVC模型中有以下属性:

[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属性自动添加 ,因此我无需手动添加。

2 个答案:

答案 0 :(得分:10)

Decimal类型创建自己的显示模板和编辑器模板视图,这样您就可以控制它的显示,然后任何类型为Decimal的Model属性都会自动使用该视图您拨打Html.DisplayFor(m => m.DecimalType)Html.EditorFor(m => m.DecimalType)

在文件夹视图&gt;中添加这些视图分享&gt; DisplayTemplates和EditorTemplates

例如,您的EditorTemplate类似于:

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

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

答案 1 :(得分: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;
        }