Write with MVC and jQuery however the data is coming null

0

I made a jQuery to get the data coming from the form. And I made a method in my controller to write to the Database. It turns out that the form data are coming null. What can it be? Below my jQuery and my method of persisting in DB.

jQuery

$(function () {

    var result = {
        //Id: $("").val(),
        Nome: $("input[name='txtNome']").val(),
        CPF: $("input[name='txtCep']").val(),
        Email: $("input[name='txtEmail']").val(),
        DataNascimento: $("input[name='txtAno']").val() + "-" + $("input[name='txtMes']").val() + "-" + $("input[name='txtDia']").val(),
        Telefone: $("input[name='txtTelefone']").val(),
        Celular: $("input[name='txtCelular']").val(),
        Endereco: $("input[name='txtLogradouro']").val(),
        Numero: $("input[name='txtNumero']").val(),
        CEP: $("input[name='txtCep']").val(),
        Complmento: $("input[name='txtComplemento']").val()
    };

    $("#btnGravarPassageiros").click(function () {
        $.ajax({
            url: '/Passo/addCliente',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "POST",
            data: JSON.stringify({ _tb_clientes: result }),
            success: function (data) {
                alert();
            },
            error: function (error) {

            }
        });
    });
});

My method in my controller .

public JsonResult addCliente(TB_CLIENTES _tb_clientes)
{

    AgaxturCmsEntities db = new AgaxturCmsEntities();

    db.TB_CLIENTES.Add(_tb_clientes);
    db.SaveChanges();

    var Result = _tb_clientes.Id;


    return Json(new { Result }, JsonRequestBehavior.AllowGet);
}

View :

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Agaxtur - 60 anos de Turismo</title>
    <meta charset="UTF-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <!-- CSS -->
    <link rel="stylesheet" href="@Url.Content("~/Content/reset.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/960_24_col.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/jquery.bxslider.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/table.css")" />
    <link rel="stylesheet" href="@Url.Content("~/Content/styles.css")" />

    <style>
        .ui-autocomplete-category {
            font-weight: bold;
            padding: .2em .4em;
            margin: .8em 0 .2em;
            line-height: 1.5;
        }

        .ui-autocomplete-loading {
            background: white url('/Images/ui-anim_basic_16x16.gif') right center no-repeat;
        }
    </style>

</head>
<body class="background-internas">
    <!-- HEADER TOPO -->
    <div class="container_24 header-menu">
        <div class="grid_6">
            <a href="/Home/Index/" title="Twitter" target="_blank"><img src="@Url.Content("~/Images/logo-agaxtur.jpg")" class="logo" /></a>
        </div>
        <div class="grid_18">
            <div class="grid_18">
                <ul>
                    <li><a href="#" title="">Lojas</a></li>
                    <li><a href="#" title="">Contato</a></li>
                    <li><a href="#" title="">Minhas Viagens</a></li>
                    <li><a href="#" title="">Minha Conta</a></li>
                    <li><a href="#" title="">Login</a></li>
                    <li class="portal-agente"><a href="#" title="">Portal do Agente</a></li>
                </ul>
            </div>
            <div class="grid_18">
                <span class="telefone">
                    <img src="image/ico-telefone.png" />
                    (11) 3067.0900
                </span>
            </div>
        </div>
    </div>
    <!-- END HEADER TOPO -->
    <!-- HEADER NAV MENU DROP DOWN -->
    <div class="container_24 nav-menu">
        <img id="loading" src="@Url.Content("~/Images/bx_loader.gif")" style="display: block; margin-left: auto; margin-right: auto" />
        <ul class="grid_24" id="menuheader"></ul>
    </div>
    <!-- END MENU HOVER -->
    <div class="container_24">
        <div class="grid_24">
            <div class="breadcrumbs">Você está em: Seleção de Pacotes</div>
        </div>
    </div>
    <!-- PROCESSO DE COMPRA  -->
    <div class="container_24 processo-compra">
        <h1>Seleção de pacotes</h1>
        <!--   ITENS QUE FORMA SELECIONADOS NA PESQUISA    -->
        <div class="itens-selecionados">
            <div class="grid_14 box-dados">
                <ul>
                    <li class="font-euro-bold">Lisboa Express</li>
                    <li>
                        <span class="font-euro-bold">Ida: </span>12/12/2013
                        <span class="font-euro-bold"> Volta: </span>12/01/2014
                    </li>
                    <li class="font-euro-bold">4 adultos</li>
                    <li><button value="novaPesquisa">Nova pesquisa</button></li>
                </ul>
            </div>
            <div class="grid_9 box-resumo">
                <div>
                    <h1>Resumo da Viagem</h1>
                </div>
                <div class="pull-left text-right">
                    <p>Pacote 2:</p>
                    <p>Voo 1 ida:</p>
                    <p>Voo 2 volta:</p>
                    <p>Total:</p>
                </div>
                <div class="pull-left">
                    <p>R$ 300,00</p>
                    <p>R$ 300,00</p>
                    <p>R$ 300,00</p>
                    <p>R$ 900,00</p>
                </div>
            </div>
        </div>
        <!--   END ITENS QUE FORMA SELECIONADOS NA PESQUISA    -->
        <!--   NAVEGAÇÃO ENTRE OS PROCESSOS DE COMPRA    -->
        <div class="grid_24 passos">
            <ul>
                <li>
                    <p>Pacotes</p>
                    <span>Passo 1</span>
                </li>
                <li>
                    <p>Aereo</p>
                    <span>Passo 2</span>
                </li>
                <li>
                    <p>Hotéis</p>
                    <span>Passo 3</span>
                </li>
                <li>
                    <p>Serviços<br>Adicionais</p>
                    <span>Passo 4</span>
                </li>
                <li>
                    <p>Resumo</p>
                    <span>Passo 5</span>
                </li>
                <li class="active">
                    <p>Pagamento</p>
                    <span>Passo 6</span>
                </li>
            </ul>
        </div>
        <!--   END NAVEGAÇÃO ENTRE OS PROCESSOS DE COMPRA    -->
        <!--   FILTROS E ORDENAÇÃO UTILIZADOS NO TOPO    -->
        <div class="grid_24 filtro">
            <h1 class="grid_9">Insira os dados do passageiro e pagamento.</h1>
        </div>
        <!--   END FILTROS E ORDENAÇÃO UTILIZADOS NO TOPO    -->
        <div class="grid_24 clearfix"></div>
        <!--   BOX QUE COMPILA O RESULTADO DA BUSCA REALIZADA PELO USUÁRIO -->

        <div class="grid_19 box-resultado">
            <div class="dados-pagamento">

                <!--    INGRESSOS E SHOWS    -->
                <div class="grid_19">
                    <h1>Confirmação dos dados</h1>
                </div>
                <!--    PRIMEIRO INGRESSO   -->
                <div class="dados">
                    <div class="form-group">
                        <div class="grid_4">
                            <label>Nome</label>
                        </div>
                        <div class="grid_14">
                            <input id="txtNome" type="text" name="txtNome" class="grid_14 required" placeholder="Nome completo" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="grid_4">
                            <label>Email</label>
                        </div>
                        <div class="grid_7">
                            <input id="txtEmail" type="email" name="txtEmail" class="grid_6  required" placeholder="Email válido" required />
                        </div>
                        <div class="grid_2">
                            <label>CPF</label>
                        </div>
                        <div class="grid_5">
                            <input id="txtCpf" type="text" name="txtCpf" class="grid_5  required" placeholder="99999999999" required />
                            @*@Html.ValidationMessageFor(model => model.)*@
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="grid_4">
                            <label>Data Nascimnento</label>
                        </div>
                        <div class="grid_14">
                            <select id="txtDia" name="txtDia" class="grid_2" required>
                                <option>Dia</option>
                            </select>
                            <select id="txtMes" name="txtMes" class="grid_2" required>
                                <option>Mês</option>
                            </select>
                            <select id="txtAno" name="txtAno" class="grid_2" required>
                                <option>Ano</option>
                            </select>

                            @*retirar após testes*@
                            <div class="form-group">
                                <div class="grid_4">
                                    <label>Qde de Passageiros</label>
                                </div>
                                <div class="grid_5">
                                    <input type="text" name="txtTesteQdePass" class="grid_4  required" placeholder="Entre com a qde de passageiros" />
                                </div>
                            </div>


                        </div>
                    </div>

                    @*Botão preenche endereço*@
                    <div class="grid_17">
                        <button value="novaPesquisa" class="btn-pular-passo pull-right" id="btnEndereco">Continuar</button>
                    </div>



                    @*A partir daqui, colocar em uma div para esconder e aparecer*@

                    <div class="grid_19 box-resultado" id="endereco" @*style="display: none"*@ >
                        <div class="form-group">
                            <div class="grid_4">
                                <label>CEP</label>
                            </div>
                            <div class="grid_14">
                                <input id="txtCep" type="text" name="txtCep" class="grid_3  required" placeholder="00000-000" required />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="grid_4">
                                <label>Endereço</label>
                            </div>
                            <div class="grid_14">
                                <input id="txtLogradouro" type="text" name="txtLogradouro" class="grid_14 required" placeholder="Endereço completo" required />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="grid_4">
                                <label>Número</label>
                            </div>
                            <div class="grid_4">
                                <input id="txtNumero" type="text" name="txtNumero" class="grid_3  required" required />
                            </div>
                            <div class="grid_2">
                                <label>Complemento</label>
                            </div>
                            <div class="grid_8">
                                <input id="txtComplemento" type="text" name="txtComplemento" class="grid_8  required" required />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="grid_4">
                                <label>Telefone</label>
                            </div>
                            <div class="grid_6">
                                <input id="txtTelefone" type="text" name="txtTelefone" class="grid_6  required" required />
                            </div>
                            <div class="grid_2">
                                <label>Celular</label>
                            </div>
                            <div class="grid_6">
                                <input id="txtCelular" type="text" name="txtCelular" class="grid_6  required" required />
                            </div>
                        </div>

                    </div>

                    @*<div class="grid_17">
                            <button value="novaPesquisa" class="btn-pular-passo pull-right">Continuar</button>
                        </div>*@
                </div>
            </div>
        </div>

        <div class="grid_19 box-resultado" @*style="display: none"*@>
            @{
                string
                    nm, dia, mes, ano, sexo, numpassaporte,
                    diavalidade, mesvalidade,
                    anovalidade, paisemissao, dados = "";

                for (int i = 1; i < 3; i++)
                {
                    nm = "txtNomePassageiro" + i;
                    dia = "txtDiaPassageiro" + i;
                    mes = "txtMesPassageiro" + i;
                    ano = "txtAnoPassageiro" + i;
                    sexo = "txtSexo" + i;
                    numpassaporte = "txtPassaporte" + i;
                    diavalidade = "txtDiaVal" + i;
                    mesvalidade = "txtMesVal" + i;
                    anovalidade = "txtAnoVal" + i;
                    paisemissao = "txtPaisEmissao" + i;

                    dados = "0" + i;


                    <div class="dados-pagamento">
                        <!--    INGRESSOS E SHOWS    -->
                        <div class="grid_19">
                            @{
                    if (i < 10)
                    {
                        <h1>Dados do Passageiro @dados</h1>
                    }
                    else
                    {
                        <h1>Dados do Passageiro @i</h1>
                    }
                            }
                        </div>
                        <!--    PRIMEIRO INGRESSO   -->
                        <div class="dados">
                            <form class="">
                                <div class="form-group">
                                    <div class="grid_4">
                                        <label>Nome do passageiro</label>
                                    </div>
                                    <div class="grid_14">
                                        <input id="@nm" type="text" name=@nm class="grid_14 required" placeholder="Nome completo" required />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="grid_4">
                                        <label>Data Nascimento</label>
                                    </div>
                                    <div class="grid_7">
                                        <select name=@dia class="grid_2" required="required">
                                            <option>Dia</option>
                                        </select>
                                        <select name=@mes class="grid_2" required>
                                            <option>Mês</option>
                                        </select>
                                        <select name=@ano class="grid_2" required>
                                            <option>Ano</option>
                                        </select>
                                    </div>
                                    <div class="grid_2">
                                        <label>Sexo</label>
                                    </div>
                                    <div class="grid_5">
                                        <select name=@sexo class="grid_3" required>
                                            <option>Sexo</option>
                                            <option>Masculino</option>
                                            <option>Feminino</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="grid_4">
                                        <label>Número do passaporte</label>
                                    </div>
                                    <div class="grid_5">
                                        <input type="number" name=@numpassaporte class="grid_4  required" required />
                                    </div>
                                    <div class="grid_2">
                                        <label>Validade</label>
                                    </div>
                                    <div class="grid_6">
                                        <select name=@diavalidade class="grid_2" required>
                                            <option>Dia</option>
                                        </select>
                                        <select name=@mesvalidade class="grid_2" required>
                                            <option>Mês</option>
                                        </select>
                                        <select name=@anovalidade class="grid_2" required>
                                            <option>Ano</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="grid_4">
                                        <label>País de emissão</label>
                                    </div>
                                    <div class="grid_5">
                                        <select name=@paisemissao class="grid_3" required>
                                            <option>País</option>
                                        </select>
                                    </div>
                                </div>
                                @*<div class="grid_17">
                                        <button value="novaPesquisa" class="btn-pular-passo pull-right">Ir para o pagamento</button>
                                    </div>*@
                            </form>
                        </div>
                    </div>

                }


            }
        </div>



        <div class="grid_19 box-resultado" id="irpagamento" @*style="display: none"*@>
            <div class="dados-pagamento">
                <div class="grid_17">
                    <button id="btnGravarPassageiros" onclick="window.location.href='/Home/Index'" value="novaPesquisa" class="btn-pular-passo pull-right">Ir para o pagamento</button>
                </div>
            </div>
        </div>

        <!--   END BOX QUE COMPILA O RESULTADO DA BUSCA REALIZADA PELO USUÁRIO -->
    </div>
    <!-- END PROCESSO DE COMPRA  -->
    <!-- FOOTER -->
    <div class="footer">
        <div class="container_24">
            <div class="grid_12">
                <a href="#" title="Twitter" target="_blank"><img src="image/ico-twitter.png" alt="Twitter" /></a>
                <a href="#" title="Facebook" target="_blank"><img src="image/ico-facebook.png" alt="Facebook" /></a>
                <a href="#" title="Pinterest" target="_blank"><img src="image/ico-pinterest.png" alt="Pinterest" /></a>
                <a href="#" title="Instangran" target="_blank"><img src="image/ico-instangran.png" alt="Instangran" /></a>
                <a href="#" title="You Tube" target="_blank"><img src="image/ico-youtube.png" alt="You Tube" /></a>
            </div>
            <div class="grid_12">
                <div class="pull-right">
                    <a href="#" title="Site Blindado" target="_blank"><img src="image/ico-site-blindado.png" class="margin-left-20" alt="Site Blindado" /></a>
                    <a href="#" title="Norton Security" target="_blank"><img src="image/ico-norton.png" class="margin-left-20" alt="Norton Security" /></a>
                    <a href="#" title="E-Bit" target="_blank"><img src="image/ico-e-bit.png" class="margin-left-20" alt="E-Bit" /></a>
                </div>
            </div>
            <ul>
                <li>
                    <div class="container_24 menu-footer" id="menufooter">
                        <ul class="grid_4" id="CategoriaInstitucional">
                            <li>Institucional</li>

                        </ul>
                    </div>
                </li>
            </ul>
        </div>
    </div>
    <!-- END FOOTER -->
    <!-- Bibliotecas JavaScript -->
    <script src="js/jquery-2.1.0.js"></script>
    <script src="js/lib/jquery-ui/jquery-ui.min.js"></script>
    <script src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui.js")"></script>
    <script src="@Url.Content("~/Scripts/Ultil.js")"></script>
    <script src="@Url.Content("~/Scripts/lib/jquery-ui/jquery-ui.min.js")"></script>
    <script src="@Url.Content("~/Scripts/Passos/Passo_06.js")"></script>

    <!-- txtDestino -->
    <script id="txtDestino" type="text/x-handlebars-template">
        <input type="text" {{#if this.required}} required="required" {{ />if}} name="txtDestino"  placeholder="Insira aqui o seu destino" class="input-11 ui-autocomplete-input" autocomplete="off" />
    </script>

    <script type="text/javascript">
        function lpad(num, size) {
            var s = num + "";
            while (s.length < size) s = "0" + s;
            return s;
        }
    </script>

    <script>
        $(function () {


            MontaMenuInstitucional();
            MontaMenuInferior();
            MontaMenuSuperiorDestino();
            /**
             * ===============================================================================================================
             *  FUNÇÃO QUE IRÁ REALIZAR A ABERTURA E FECHAMENTO DE CADA UM DOS DETALHES DE CADA PRODUTO,
             *  Funcionamento
             *  -   para cada div de detalhe do produto, devemos criar um ID único e o mesmo ser
             *      referenciado no HREF do tipo de detalhe
             * ===============================================================================================================
             */
            $('.detalhes a').click(function (e) {
                e.preventDefault();
                $('.detalhes a').each(function (key, element) {
                    $($(element).attr('href')).slideUp();
                }).parent().removeClass('active');
                $($(this).attr('href')).slideDown();
                $(this).parent().addClass('active');
            });
        });
    </script>


    <script type="text/javascript">

        $(function () {

            $("#btnEndereco").click(function () {
                $.ajax({
                    url: '/Passo/PreencheEndereco',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    data: JSON.stringify({ _cpf: $("#txtCpf").val() }),
                    success: function (data) {

                        $(data.Result).each(function () {

                            $("#txtCep").val(this.CEP);
                            $("#txtLogradouro").val(this.Endereco);
                            $("#txtNumero").val(this.Numero);
                            $("#txtComplemento").val(this.Complmento);
                            $("#txtTelefone").val(this.Telefone);
                            $("#txtCelular").val(this.Celular);

                        });

                    },
                    error: function (error) {

                    }
                });
            });
        });

    </script>

    <script type="text/javascript">

        $(function () {

            var result = {
                //Id: $("").val(),
                Nome:           $("input[name='txtNome']").val(),
                CPF:            $("input[name='txtCep']").val(),
                Email:          $("input[name='txtEmail']").val(),
                DataNascimento: $("input[name='txtAno']").val() + "-" + $("input[name='txtMes']").val() + "-" + $("input[name='txtDia']").val(),
                Telefone:       $("input[name='txtTelefone']").val(),
                Celular:        $("input[name='txtCelular']").val(),
                Endereco:       $("input[name='txtLogradouro']").val(),
                Numero:         $("input[name='txtNumero']").val(),
                CEP:            $("input[name='txtCep']").val(),
                Complmento:     $("input[name='txtComplemento']").val()
            };

            $("#btnGravarPassageiros").click(function () {
                $.ajax({
                    url: '/Passo/addCliente',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    data: JSON.stringify({ _tb_clientes: result }),
                    success: function (data) {
                        alert();
                    },
                    error: function (error) {

                    }
                });
            });
        });

    </script>

</body>
</html>
    
asked by anonymous 14.03.2014 / 19:21

1 answer

1

This addCliente method is well out of the Web API standard. I would do something like this:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using MeuProjeto.Models;

namespace MeuProjeto.Controllers
{
    public class ClientesController : ApiController
    {

        // POST api/Clientes
        [ResponseType(typeof(TB_CLIENTES))]
        public async Task<JsonResult> PostCliente(TB_CLIENTES _tb_clientes)
        {
            AgaxturCmsEntities db = new AgaxturCmsEntities();

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.TB_CLIENTES.Add(_tb_clientes);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ClienteExists(_tb_clientes.Id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return Json(new { _tb_clientes.Id }, JsonRequestBehavior.AllowGet);
        }
    }
}

In this way, I check in the context if the client already exists, I raise conflicts if this occurs and return the correct status on screen.

    
14.03.2014 / 19:42