I have two properties in a model class:
public int? IntTest { get; set; }
public decimal? DecimalTest { get; set; }
Which I then render with:
@Html.EditorFor(model => model.IntTest, new { htmlAttributes = new { @class = "form-control"} })
@Html.EditorFor(model => model.DecimalTest, new { htmlAttributes = new { @class = "form-control"} })
I'd expected both of them to render as html inputs of type number, but the decimal one doesn't, I get:
<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="" />
The decimal value is rendered as type="text"
whereas the int is registered as type="number"
.
This question implies that isn't the expected behaviour so am I doing something wrong?
If that is the expected behaviour, is there any way of changing EditorFor
to render all decimals as type="number"
, rather than having to add type = "number"
in the htmlAttributes
of every decimal field?
The html you are seeing is the default behavior. The
EditorFor()
methods use the default templates (unless you have created a customEditorTemplate
for the type) as defined in TemplateHelpers.cs.For typeof
int
(andbyte
andlong
), it uses theNumberInputTemplate
, and for typeofdecimal
it uses theDecimalTemplate
. These templates are defined in DefaultEditorTemplates.cs which are fordecimal
which in turn calls
and for
int
Note that the
NumberInputTemplate
defines theinputType
as"number"
which adds thetype="number"
attribute, where asStringTemplate
uses the defaultinputType
which generatestype="text"
.To add
type="number"
for adecimal
, then you need to manually add the attribute, using eitheror
An alternative would be to create a custom
EditorTemplate
in the/Views/Shared/EditorTemplates/Decimal.cshtml
for typeofdecimal
, for exampleand in the main view use
Another alternative would be to create you own
HtmlHelper
extension method (say@Html.DecimalFor(...)
) to generate the html.