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 customEditorTemplatefor the type) as defined in TemplateHelpers.cs.For typeof
int(andbyteandlong), it uses theNumberInputTemplate, and for typeofdecimalit uses theDecimalTemplate. These templates are defined in DefaultEditorTemplates.cs which are fordecimalwhich in turn calls
and for
intNote that the
NumberInputTemplatedefines theinputTypeas"number"which adds thetype="number"attribute, where asStringTemplateuses the defaultinputTypewhich 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
EditorTemplatein the/Views/Shared/EditorTemplates/Decimal.cshtmlfor typeofdecimal, for exampleand in the main view use
Another alternative would be to create you own
HtmlHelperextension method (say@Html.DecimalFor(...)) to generate the html.