How to insert values that have "," as decimal separator?

Asked

Viewed 237 times

1

Hello, I am making a product registration using . Net Core 3.1 and I have the following problem: In the product register there is a field to insert the value of the product, however when inserting a value with a comma, 300,50 for example, when exiting the input, the following message is returned : The field Price must be a number.. What can I do to insert values with "," ?

Code:

Product Class - Preco field

    [Required(ErrorMessage = "O campo <b>Preço</b> deve ser preenchido!")]
    [Display(Name = "Preço")]
    [DataType(DataType.Currency)]       
    public decimal Preco { get; set; }

In the Product class I make a select * from product id_Produto = @id_Produto and the attributes are fed as follows:

Produto produto = new Produto()
{
    ProdutoId = Convert.ToInt32(rdr["id_Produto"]),
    Descricao = rdr["descricao"].ToString(),
->  Preco = Convert.ToDecimal(rdr["preco"]),
    Status = rdr["status"].ToString(),
    Id_Categoria = Convert.ToInt32(rdr["id_Categoria"])

};

In the Edit.cshtml is like this:

<div class="form-group">
    <label asp-for="Preco" class="control-label"></label>
    <input asp-for="Preco" class="form-control"/>
    <span asp-validation-for="Preco" class="text-danger"></span>
</div>
  • There is a way using System.Globalization of changing the decimal separator, gives a search. A practical solution: "35.50". Replace(",",".");

  • Good evening Edney, thanks for your help! I did as Leonardo said, the only thing different I needed to do was instead of using decimal.tryParse was to use Convert.Todecimal.

  • PRICE.REPLACE(",",""). REPLACE(",","."); AND BE HAPPY

1 answer

0

One way to solve your problem is to create a Viewmodel and change the attribute to string by converting to the Product class in the controller, so you can validate your field without touching your Model directly.

Create the Viewmodel class and change your .cshtml to receive it:

public class ProdutoViewModel
{
    public int ProdutoId { get; set; }
    public string Descricao { get; set; }
    public string Preco { get; set; }
    public string Status { get; set; }
    public int Id_Categoria { get; set; }
}

And in Controller, make the following changes:

[HttpPost]
public async Task<IActionResult> Edit(ProdutoViewModel produtoViewModel)
{
    // Caso não seja um número válido, será retornado 0
    decimal.TryParse(produtoViewModel.Preco.Replace(".", string.Empty).Replace(",","."), out decimal preco);

    Produto produto = new Produto()
    {
        ProdutoId = produtoViewModel.ProdutoId,
        Descricao = produtoViewModel.Descricao,
        Preco =  preco,
        Status = produtoViewModel.Status,
        Id_Categoria = produtoViewModel.Id_Categoria 
    };

    // Sua lógica para gravar no banco

    return View(produtoViewModel);
}

Note that we replace the point with empty, and the comma per point, so when you receive the number "300.50" it will be transformed into "300.50", being a valid number.

We also do the Tryparse, to ensure that an Exception is not fired if it is not a number, so it returns the value 0.

Don’t forget to validate in HTML as well, to ensure data consistency.

  • Good night, Leonardo, dear! Tryparse I do not know why I was taking the string value "350.00" for example, and putting together the numbers, getting 35000, then I looked on the internet, a solution I found was to store in a string the result that was generated by replace and then pass to the Preco attribute of the product object, the following: Convert.Todecimal(price, Cultureinfo.InvariantCulture.Numberformat)where the price parameter is the string that stores the value 350.00

Browser other questions tagged

You are not signed in. Login or sign up in order to post.