您看到的 html 是默认行为。这些方法使用 TemplateHelpers.cs 中定义的默认模板(除非您为该类型EditorFor()
创建了自定义模板) 。EditorTemplate
对于 typeof int
(and byte
and 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
定义了添加属性的inputType
as ,其中 as 使用生成的默认值。"number"
type="number"
StringTemplate
inputType
type="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.cshtml
for 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。