2

I'm having a problem with the forms validation of asp.net core when using a decimal field in my viewmodel, where the input's value receives a number with a comma but upon the submit it doesn't permit it..

ViewModel:

public class MyViewModel
{
    public decimal Price { get; set; }
}

Razor page:

<div class="form-group row">
    <label asp-for="Price" req-asterisk="true" class="col-md-3 col-lg-2 col-form-label"></label>
    <div class="col-md-9 col-lg-10">
         <input asp-for="Price" class="form-control" rows="4" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
</div>

So, if for example the Price property takes 4000, the input takes 4000,00 and if I click submit it says "The field Price must be a number."

Haytam
  • 4,643
  • 2
  • 20
  • 43
  • Tried this https://stackoverflow.com/questions/45881119/asp-net-core-localization-decimal-field-dot-and-comma?noredirect=1&lq=1 but it only works client-side. – Haytam Apr 29 '18 at 21:02
  • What you are looking for is not just validation. You need a string to be converted to a decimal in the model and then validated. – Neville Nazerane Apr 30 '18 at 00:19

1 Answers1

0

Considering your Price field needs to contain the value, you will need to use a string to access your value. Here is a sample of what you can do with a string property with some memory saving options:

public class MyViewModel
{

    private string _priceDisplay;
    [DataType(DataType.Currency)]
    public string PriceDisplay {
        get => _priceDisplay ?? _price.ToString();
        set => _priceDisplay = value;
    }

    private decimal? _price;
    public decimal Price
    {
        get => _price ?? decimal.Parse(PriceDisplay);
        set => _price = value;
    }


}

You can now map your input to PriceDisplay

Neville Nazerane
  • 6,622
  • 3
  • 46
  • 79