Home > other >  can't pass decimal value to model parameter
can't pass decimal value to model parameter

Time:09-08

I have a Dto Like this

public class AgeDto
{
    public long Id { get; set; }
    [Required]
   
    [Precision(2, 1)]
    public decimal LowAge { get; set; }

    [Precision(2, 1)]
    public decimal? HighAge { get; set; }
}

and my for is like this

 @model AgeDto
 <form  method="post" asp-action="Index" asp-controller="ages">
                        <div >
                            <div > From</div>
                            <div>
                                <input asp-for="LowAge" type="text" >
                                <span asp-validation-for="LowAge" ></span>
                            </div>
                        </div>

                        <div >
                            <div > To</div>
                            <div>
                                <input asp-for="HighAge" type="text" >
                                <span asp-validation-for="HighAge" ></span>
                            </div>
                        </div>
                        <div  >

                            <div >
                                <input asp-for="Id" type="hidden" />
                                <input  type="submit" value="Register" />
                            </div>

                        </div>
                    </form>

and controller like this

   [HttpPost]
    public async Task<IActionResult> Index(AgeDto agesDto)
    {
    //           does something
    }

althought the LowAge and HighAge are decimal, but if enter 1.5 or 2.5 or any number with fractional it passes value 0 on agesDto on Controller why is that so?

CodePudding user response:

0 is the default value for your model properties. It's most likely the modelbinding doesnt recognize any valid values to apply to the properties.

Most of the time this is due to culture conflicts for the separator, especially since you're using text-inputs for the properties.

See: https://stackoverflow.com/a/53120061/6803592

  •  Tags:  
  • c#
  • Related