TheBlackOne
TheBlackOne

Reputation: 23

Binding removes decimal separator

I have a problem with the Bind function in C# Asp.Net when working with decimal numbers. The decimal separator is being removed when the value is bound to the object.

For Example:

Since this is likely to be relevant: I am from Germany and therefore having German as languagesetting in all applications. I have not made any changes in that regard within the code.

I have already tried different datatypes and HTML-Input-Types. Any Idea on how to solve this?

Here is my code.

 public class ExampleClass
    {
        public int id { get; set; }
        public string Name { get; set;}
        public double Number { get; set; }
    }
 <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Number" class="control-label"></label>
                <input asp-for="Number" type ="number" min="0" max="100" class="form-control" />
                <span asp-validation-for="Number" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>

The database has been created with entity framework migrations, which has resulted in a "float" type for the column in question.

Upvotes: 1

Views: 1398

Answers (1)

Michel
Michel

Reputation: 68

The decimal binding in ASP.NET core is not culture invariant by default. The model binding depends on the server culture. You can do one of two things: create a custom model binder or (the way i solved this for my self) setting the decimal seperator for your application. In the Configure method in the Startup.cs you can define and set your culture. So for you it would be something like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var cultureInfo = new CultureInfo("de-DE");
cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
cultureInfo.NumberFormat.CurrencyDecimalSeparator = ".";
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

// Other configuring statements
}

Upvotes: 1

Related Questions