Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using "asp-for" on a double or decimal property results in a type=text input

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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." 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading