3

我在模型类中有两个属性:

public int? IntTest { get; set; }
public decimal? DecimalTest { get; set; }

然后我渲染:

@Html.EditorFor(model => model.IntTest, new { htmlAttributes = new { @class = "form-control"} })
@Html.EditorFor(model => model.DecimalTest, new { htmlAttributes = new { @class = "form-control"} })

我希望它们都呈现为数字类型的 html 输入,但小数点没有,我得到:

<input class="form-control text-box single-line" data-val="true" data-val-number="The field IntTest must be a number." id="IntTest" name="IntTest" type="number" value="" />
<input class="form-control text-box single-line" data-val="true" data-val-number="The field IntTest must be a number." id="DecimalTest" name="DecimalTest" type="text" value="" />

十进制值呈现为,type="text"而 int 注册为type="number".

这个问题暗示这不是预期的行为,所以我做错了什么?

如果这是预期的行为,是否有任何方法可以更改EditorFor将所有小数呈现为type="number",而不必添加每个小数字段的type = "number"htmlAttributes

4

1 回答 1

4

您看到的 html 是默认行为。这些方法使用 TemplateHelpers.cs 中定义的默认模板(除非您为该类型EditorFor()创建了自定义模板) 。EditorTemplate

对于 typeof int(and byteand long),它使用NumberInputTemplate,对于 typeofdecimal它使用DecimalTemplate。这些模板在DefaultEditorTemplates.cs中定义,用于decimal

internal static string DecimalTemplate(HtmlHelper html)
{
    if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model)
    {
        html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, "{0:0.00}", html.ViewContext.ViewData.ModelMetadata.Model);
    }
    return StringTemplate(html);
}

这反过来又调用

internal static string StringTemplate(HtmlHelper html)
{
    return HtmlInputTemplateHelper(html);
}

并且对于int

internal static string NumberInputTemplate(HtmlHelper html)
{
    return HtmlInputTemplateHelper(html, inputType: "number");
}

请注意,NumberInputTemplate定义了添加属性的inputTypeas ,其中 as 使用生成的默认值。"number"type="number"StringTemplateinputTypetype="text"

要添加type="number"a decimal,您需要手动添加属性,使用

@Html.EditorFor(m => m.DecimalTest, new { htmlAttributes = new { type = "number", @class = "form-control"} })

或者

@Html.TextBoxFor(m => m.DecimalTest, new { type = "number", @class = "form-control"})

另一种方法是EditorTemplate/Views/Shared/EditorTemplates/Decimal.cshtmlfor typeof中创建一个自定义decimal,例如

@model decimal?
@{
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    if (!attributes.ContainsKey("type"))
    {
         attributes.Add("type", "number");
    }
    string formatString = ViewData.ModelMetadata.DisplayFormatString ?? "{0:N2}";
}
@Html.TextBoxFor(m => m, formatString , attributes)

并在主视图中使用

@Html.EditorFor(model => model.DecimalTest, new { htmlAttributes = new { @class = "form-control"} })

另一种选择是创建您自己的HtmlHelper扩展方法(例如@Html.DecimalFor(...))来生成 html。

于 2018-08-26T00:31:10.443 回答