According to https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0#the-input-tag-helper, asp-for should change the input type attribute according to the bound property. However, that’s not what I’m getting. I’ve created a new ASP.NET 6 (MVC) webapp and created a model:
public class MyModel
{
public double MyProperty { get; set; } = 1.45d;
}
and Index.cshtml to
@model MyModel;
<div class="text-center">
<input asp-for="MyProperty"/>
</div>
When I inspect the element with Firefox’s dev tools, I get:
<input type="text" data-val="true" data-val-number="The field MyProperty must be a number." data-val-required="The MyProperty field is required." id="MyProperty" name="MyProperty" value="">
Shouldn’t it be type=number?
>Solution :
It looks like the documentation does not match with the implementation
The source code on github shows below mapping of data types to input types.
Notice how Double is being mapped to InputType.Text.
private static readonly Dictionary<string, string> _defaultInputTypes =
new(StringComparer.OrdinalIgnoreCase)
{
// ...
{ nameof(Byte), "number" },
{ nameof(SByte), "number" },
{ nameof(Int16), "number" },
{ nameof(UInt16), "number" },
{ nameof(Int32), "number" },
{ nameof(UInt32), "number" },
{ nameof(Int64), "number" },
{ nameof(UInt64), "number" },
{ nameof(Single), InputType.Text.ToString().ToLowerInvariant() },
{ nameof(Double), InputType.Text.ToString().ToLowerInvariant() },
{ nameof(Boolean), InputType.CheckBox.ToString().ToLowerInvariant() },
{ nameof(Decimal), InputType.Text.ToString().ToLowerInvariant() }
// ...
};
Do notice that for e.g. a Double a data-val-number attribute is being rendered as part of the unobtrusive input validation.
data-val-number="The field MyProperty must be a number."