How to pass javascript values to C#

Asked

Viewed 378 times

0

I have a Client class, where a customer can have several benefits as you can see in the last property.

public class Cliente
    {
        /// <summary>
        /// Id
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// CEP
        /// </summary>
        public string CEP { get; set; }

        /// <summary>
        /// Cidade
        /// </summary>
        public string Cidade { get; set; }

        /// <summary>
        /// E-mail
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// Estado
        /// </summary>
        public string Estado { get; set; }

        /// <summary>
        /// Logradouro
        /// </summary>
        public string Logradouro { get; set; }

        /// <summary>
        /// Nacionalidade
        /// </summary>
        public string Nacionalidade { get; set; }

        /// <summary>
        /// Nome
        /// </summary>
        public string Nome { get; set; }

        /// <summary>
        /// Sobrenome
        /// </summary>
        public string Sobrenome { get; set; }

        /// <summary>
        /// Telefone
        /// </summary>
        public string Telefone { get; set; }

        /// <summary>
        /// Cpf
        /// </summary>
        public string Cpf { get; set; }

        public List<Beneficiario> Beneficiarios { get; set; }
    } 

Classe Beneficiario:

public class Beneficiario
    {
        /// <summary>
        /// Id
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// Cpf
        /// </summary>
        public string CpfBeneficiario { get; set; }

        /// <summary>
        /// Nome
        /// </summary>
        public string NomeBeneficiario { get; set; }

        /// <summary>
        /// Id do Cliete
        /// </summary>
        public int IdCliente { get; set; }

    }

JS Code:

    var rowIndex = -1;
var beneficiarios = [];

$(document).ready(function () {
    $('#formCadastro').submit(function (e) {
        e.preventDefault();
        var lista = document.getElementById('tbLista').rows;    
        for (var i = 1; i < lista.length; i++) {
            beneficiarios.push(JSON.stringify({ "cpf": lista[i].cells[0].innerHTML, "nome": lista[i].cells[1].innerHTML }));
        }
        $.ajax({
            url: urlPost,
            method: "POST",
            data: {
                "NOME": $(this).find("#Nome").val(),
                "CEP": $(this).find("#CEP").val(),
                "Email": $(this).find("#Email").val(),
                "Sobrenome": $(this).find("#Sobrenome").val(),
                "Nacionalidade": $(this).find("#Nacionalidade").val(),
                "Estado": $(this).find("#Estado").val(),
                "Cidade": $(this).find("#Cidade").val(),
                "Logradouro": $(this).find("#Logradouro").val(),
                "Telefone": $(this).find("#Telefone").val(),
                "Cpf": $(this).find("#Cpf").val(),
                "Beneficiarios": JSON.stringify(beneficiarios)
            },
            error:
                function (r) {
                    if (r.status == 400)
                        ModalDialog("Ocorreu um erro", r.responseJSON);
                    else if (r.status == 500)
                        ModalDialog("Ocorreu um erro", "Ocorreu um erro interno no servidor.");
                },
            success:
                function (r) {
                    ModalDialog("Sucesso!", r)
                    $("#formCadastro")[0].reset();
                }
        });
    });
});

Controller:

[HttpPost]
        public JsonResult Alterar(ClienteModel model)
        {
            BoCliente bo = new BoCliente();

            if (!this.ModelState.IsValid)
            {
                List<string> erros = (from item in ModelState.Values
                                      from error in item.Errors
                                      select error.ErrorMessage).ToList();

                Response.StatusCode = 400;
                return Json(string.Join(Environment.NewLine, erros));
            }
            else
            {
                var cpf = RemoverCaracteresEspeciais(model.Cpf);
                var existeCPF = bo.VerificarExistencia(cpf);
                if (existeCPF)
                {
                    Response.StatusCode = 400;
                    return Json("O Cpf já está cadastrado.");
                }
                else
                {
                    if (Validacoes.ValidaCpf(cpf))
                    {
                        bo.Alterar(new Cliente()
                        {
                            Id = model.Id,
                            CEP = model.CEP,
                            Cidade = model.Cidade,
                            Email = model.Email,
                            Estado = model.Estado,
                            Logradouro = model.Logradouro,
                            Nacionalidade = model.Nacionalidade,
                            Nome = model.Nome,
                            Sobrenome = model.Sobrenome,
                            Telefone = model.Telefone,
                            Cpf = cpf
                        });

                        return Json("Cadastro alterado com sucesso");
                    }
                    else
                    {
                        Response.StatusCode = 400;

                        return Json(string.Join(Environment.NewLine, "O cpf digitado é inválido."));
                    }
                }
            }
        }

I have a table where I add Cpf and name of each benefit to that respective client, I can pass all data to my controller but I have no idea what it would be like to pass the values of table tb. My question is this, how can I pass values from a table on the front end via ajax to my list of benefits of the Client class in c#?

  • Do you want to know how to pass some information from a "Front End" table to the "Back End" controller? What would be the information? Can display HTML code?

  • that’s right, when you get to the back end that is c# the list is coming zeroed

1 answer

0


To parse correctly, you must put the same name in the attributes (Model/View).

This line: beneficiarios.push(JSON.stringify({ "cpf": lista[i].cells[0].innerHTML, "nome": lista[i].cells[1].innerHTML }));

should look like this: beneficiarios.push(JSON.stringify({ "CpfBeneficiario": lista[i].cells[0].innerHTML, "NomeBeneficiario": lista[i].cells[1].innerHTML }));

  • Those were the same names thank you.

Browser other questions tagged

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