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

タイプの独自の Display Template ビューと Editor Template ビューを作成します。Decimalこれにより、その表示を制御できます。その後、そのタイプの Model プロパティは、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 に答える