Problem with binding to double value from view form to model property in ASP.NET Core

257 Views Asked by At

I have a little problem. In ASP.NET Core, in view in form I want to enter double value with decimal point (in Czech with dot) and it doesn't want to take either one (for dot: the value '1.5' is not valid for... for comma: the field .... must be a number).

The value doesn't want to bind to the double property (same problem with decimal). There must be something basic that I'm overlooking.

My controller:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("Id,Name,Type,ApiId,Amount,InvestedMoney")] CommodityDto     commodity)
{
    if (ModelState.IsValid)
    {
        portfolioCommodityManager.Add(commodity);
        return RedirectToAction(nameof(Index));
    }

    return View(commodity);
}

My property:

public double Amount { get; set; }

My view:

<label asp-for="Amount" class="control-label fw-bold"></label>
<input asp-for="Amount" class="form-control" />
<span asp-validation-for="Amount" class="text-danger"></span>

This does not work:

services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new RequestCulture("cs-CZ");
});

---------

[DisplayFormat(DataFormatString = "{0:0.0}", ApplyFormatInEditMode = true)]
public double Amount { get; set; }
1

There are 1 best solutions below

9
ctyar On

You need to add this to your Program.cs:

var supportedCultures = new[] { new CultureInfo("cs-CZ") };
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("cs-CZ"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});

Please note this will disable the other cultures likes en-US so you may want to add that too.