Home > Mobile >  Form submitting wrong value from float input in ASP.NET MVC
Form submitting wrong value from float input in ASP.NET MVC

Time:10-22

Today I stumbled across a problem with the number input in a hmtl Form. I'm trying to get an Input from the User in form of a float. For this case i use the Input tag as following (Sorry for the English/German names):

<input asp-for="TBE_Leitwert" type="number" step="0.1"   placeholder="Leitwert (mS)" />

Somehow after submitting the form I don't get the float value. It seems like the Input is ignoring the separator at all, Example:

The User puts in the value 1,1 but submitted was 11.

Value entered from a user:

Value entered from a user

Value from submitted the form:

Value from submitted form

The same problem results, even if I put the value 1.1 so it doesn't matter if I take the dot or comma, the value still is submitted wrong as 11

Is there any way to get the right float values from submitting the form without using JS or AJAX?

Edit: I made a super minimal reproducible exampele.

Index Page:

@model TestModel
@{
    ViewData["Title"] = "Home Page";
}

<div >
    <form asp-controller="Home" asp-action="GetValue">
        <input asp-for="WantedValue" type="number" step="0.1" />
        <button type="submit">Test</button>
    </form>
</div>

HomeController just added this 1 function:

public IActionResult GetValue(TestModel test)
{
    return RedirectToAction("Index");
}

Model:

public class TestModel
{
    public double WantedValue { get; set; }
}

it is still the same, if i enter a float value on the index:

Value entered by User on Index

the Controller still gets a wrong value:

Wrong Value received from Form

since i entered "1,1" on the Index site i was expecting to get the value "1,1" in the controller. Same with the Value "1.1"

CodePudding user response:

You might need to set globalization culture in your project.

In asp.net core, add it in Startup.Configure:

var cultures = new[]
{
 new CultureInfo("en-US"),
 new CultureInfo("de"),
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-US"),
    SupportedCultures = cultures,
    SupportedUICultures = cultures
});

CodePudding user response:

I know it's not the right way to solve the problem but it works. Try to use input type text instead of number like:

<input type="text" />

And then in the controller convert it to double in this way:

var number = collection["Number"];
var numberr = double.Parse(number.Replace('.', ','));

I hope this help you.

  • Related