spalkie walkie
spalkie walkie

Reputation: 21

ASP Net Core decimal input with period turns into a whole number

I have an input field which a price which is in the model a decimal.

<div class="form-group">
 <label asp-for="Price" class="control-label">Price</label>
 <input asp-for="Price" class="form-control"/>
</div>
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal Price { get; set; }

When I POST the input field with a comma the page returns a validation error,
when I POST with a period, the price is received as a whole number.
For example when I put the price as 7.00 I receive 700 in my controller.

enter image description here

Upvotes: 0

Views: 3176

Answers (2)

Sahil Kataria
Sahil Kataria

Reputation: 30

ASP Net Core decimal input with period turns into a whole number:-

You just only need to convert the input value to decimal.

It can be achived by change the :

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

to :

<input type="number" required name="Price" min="0" value="0" step=".01">

Upvotes: 0

Yehor Androsov
Yehor Androsov

Reputation: 6162

nl-NL culture uses comma as decimal separator. You can override current culture`s number format for each request with this code

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        var currentThreadCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
        currentThreadCulture.NumberFormat = NumberFormatInfo.InvariantInfo;

        Thread.CurrentThread.CurrentCulture = currentThreadCulture;
        Thread.CurrentThread.CurrentUICulture = currentThreadCulture;

        await next();
    });
    ...
}

Upvotes: 4

Related Questions