3

我在 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 属性,所以我不必手动添加它。

4

2 回答 2

10

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

在文件夹Views > Shared > DisplayTemplates 和 EditorTemplates中添加这些视图

例如,您的 EditorTemplate 将类似于:

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

@Html.TextBoxFor(x => x, new {data-type = "decimal"})
于 2012-05-31T09:12:31.997 回答
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;
        }
于 2012-08-13T12:11:22.910 回答