Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-1.0

How to bind nullable decimal values


I'm having problems with ASP.NET Core MVC and decimal? value.

I have the following view model:

 public class BlobViewModel
 {
    public int Id { get; set; }
    public int? IntegerValue { get; set; }
    public string StringValue { get; set; }
    [DataType(DataType.Date)]
    public DateTime? DateValue { get; set; }
    public decimal? DecimalValue { get; set; }
 }

And the following input element in my view

<input asp-for="DecimalValue" class="form-control" />

When I enter a decimal value, e.g. "68.5" or "68,5" and tab out of the input element, I get the following error:

The value '68.5' is not valid for DecimalValue.

I have tried with the [DataType(DataType.Currency)] attribute above the property, but I can't seem to get the binding to work. The other properties binds as expected.

Does anyone have an idea for how I accomplish this?


Solution

  • The error you get occurs if you local Windows settings isn't set to US localization and you are using the default asp.net template jquery validation to validate decimal values. The errors should occur irrespective if your decimals are nullable or not

    In ASP.NET Core I don't think you can force the localization to US in the web.config as you get in this answer in the same way you can for ASP.NET MVC5 and earlier, so you will have to add javascript to override the jquery.validate.js as mentioned as an answer to the same question.

    create a js file called validationlocalization and put it in your wwwroot\js folder with the following contents

    $.validator.methods.range = function (value, element, param) {
        var globalizedValue = value.replace(",", ".");
        return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
    }
    
    $.validator.methods.number = function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
    }
    

    In the cshtml pages that require decimal validation add a reference to the javascript file to your scripts section. Make sure it is added after an reference to the existing _ValidationScriptsPartial.

    @section Scripts {
    
         ...
    
         <script src="~/js/validationlocalization.js"></script>
    

    More detail on this workaround