Format value received in JSON C#

Asked

Viewed 111 times

0

After returning the value to my form, I want to format it to show the decimals correctly. I’ve made several attempts using jQuery Mask, but I haven’t had any success. I appreciate if anyone can help.

 $(document).ready(function () {



            $("#categoriaPrecificacao").change(function () {

                var categoria_selecionada = $(this).children("option:selected").val();

                var urlCompleto = "/Estacionar/ObterValorHoraPrecificacao/";

                $.ajax({
                    dataType: 'json',
                    method: "GET",
                    url: urlCompleto,
                    data: { id: categoria_selecionada },
                    success: function (data) {
                        console.log(data["results"].valorHora);
                        $(".ValorHora").val(data["results"].valorHora);
                        $('.ValorHora').mask('#.##0,00', { reverse: true });
                    }
                });

            });


        });

inserir a descrição da imagem aqui

  • a doubt, the script is even applied? no errors in the right console?

  • @Ricardopunctual, no error, the answer is coming correctly

  • @Ricardopontual, I already found a solution, but thank you

1 answer

0


The solution was to return the value to the already formatted view.

Controller:

[HttpGet, ActionName("ObterValorHoraPrecificacao")]
public async Task<IActionResult> ObterValorHoraPrecificacao(Guid id)
{
    var dados = _mapper.Map<PrecificacaoViewModel>(await _precificacaoRepository.ObterPorId(id));
    var valorFormatado = string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:C}", dados.ValorHora).Replace("R","").Replace("$","");

    return Json(new
    {
        results = valorFormatado
    });

}

Jquery

    $("#categoriaPrecificacao").change(function () {

        var categoria_selecionada = $(this).children("option:selected").val();

        var urlCompleto = "/Estacionar/ObterValorHoraPrecificacao/";

        $.ajax({
            dataType: 'json',
            method: "GET",
            url: urlCompleto,
            data: { id: categoria_selecionada },
            success: function (data) {
                console.log(data["results"]);
                $(".ValorHora").val(data["results"]);

            }
        });

    });

Upshot:

inserir a descrição da imagem aqui

  • Okay, I was just about to say the same thing. I only saw that in your formatting you replace the characters "R$", the C# already format for you also in numeric format only, just in the link use the C as format, use the N, will format the same way but without the R$. It could be done like this var valorFormatado = dados.ValorHora.ToString("N2", new CultureInfo("pt-br")). In short, the result would be the same

  • @Robsonsilva, I’ll use your tip, thanks!

Browser other questions tagged

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