Send two models to a View

2

I have two Models: TBFuncionario and TBEndereço :

namespace Lamar.Dominio.Entidade
{
    public class TBFuncionario
    {
        public int TBFUNCIONARIOID { get; set; }
        public string MATRICULA { get; set; }
        [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:dd/MM/yyyy}")]
        public DateTime? DTADMISSAO { get; set; }
        public string NMFUNCIONARIO { get; set; }
        public bool STATUS { get; set; }        
        public string CPF { get; set; }
        public virtual ICollection<TBEndereco> TBEndereco { get; set; }
    }
}

public class TBEndereco
    {
        [Key]
        public int TBENDERECOID { get; set; }
        
        public int TBFUNCIONARIOID { get; set; }
        public string LOGRADOURO { get; set; }
        public string NUMLOGRADOURO { get; set; }
        public string COMPLEMENTO { get; set; }
        public string BAIRRO { get; set; }
        public string CEP { get; set; }
        [ForeignKey("TBFUNCIONARIOID")]
        public virtual TBFuncionario TBFuncionario { get; set; }
    }

Context file:

public class LMCtx : DbContext
    {
       public LMCtx () : base ("LMCtx") { }

        public DbSet<TBFuncionario> Funcionarios { get; set; }
        public DbSet<TBEndereco> Enderecos { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<TBFuncionario>().ToTable("TBFuncionario");
            modelBuilder.Entity<TBEndereco>().ToTable("TBEndereco");

            base.OnModelCreating(modelBuilder);

            
        }
    }

Interface Class:

namespace Lamar.Dominio.Interface
{
    public interface IFuncionario
    {
        List<TBFuncionario> ListarFuncionario();
        TBFuncionario ObterFuncionarioPorId(int? id);
        void InsereFuncionario(TBFuncionario pFuncionario);
        void AtualizarFuncionario(TBFuncionario pFuncionario);
        List<TBEndereco> ListarEnderecoFuncionario(int? id);
    }
}

Repository Class:

namespace Lamar.Dominio.Repositorio
{
    public class FuncionarioRepositorio: IFuncionario
    {
        private readonly LMCtx _repositorio = new LMCtx();

        public void InsereFuncionario(TBFuncionario pFuncionario)
        {
            var _model = new TBFuncionario
            {
                STATUS = pFuncionario.STATUS,
                DTADMISSAO = pFuncionario.DTADMISSAO,
                MATRICULA = pFuncionario.MATRICULA,
                NMFUNCIONARIO = pFuncionario.NMFUNCIONARIO,
                CPF = pFuncionario.CPF
            };
            _repositorio.Funcionarios.Add(_model);
            _repositorio.SaveChanges();
        }
    }
}

The Controller:

[HttpPost]
public ActionResult Create(TBFuncionario tBFuncionario)
{
if (ModelState.IsValid)
{
_IRepositorio.InsereFuncionario(tBFuncionario);
return RedirectToAction("List");
}

return View(tBFuncionario);
}

View:

@model Lamar.Dominio.Entidade.TBFuncionario
@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/Administrativo/Views/Shared/_AdministrativoLayout.cshtml";
}
<div class="form-horizontal">
    <div class="col-sm-offset-0">
        @Html.ActionLink("CANCELAR", "List", "Funcionario", null, new { @class = "btn btn-info" })
    </div>
</div>
<br />
<div id="dialog-confirm" class="modal"></div>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <fieldset class="text-info alert-info">
        <legend class="bg-success h4">DADOS PESSOAIS</legend>

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.TBFUNCIONARIOID)
            <div class="form-group">
                <div class="col-sm-offset-1">
                    <div class="col-sm-1">
                        NOME
                    </div>
                    <div class="col-sm-11">
                        @Html.EditorFor(model => model.NMFUNCIONARIO, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.NMFUNCIONARIO, "", new { @class = "text-danger" })
                        <div id="divNom" class="text-danger"></div>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-1">
                    <div class="col-sm-1">
                        ADMISSÃO
                    </div>
                    <div class="col-sm-11">
                        @Html.EditorFor(model => model.DTADMISSAO, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.DTADMISSAO, "", new { @class = "text-danger" })
                        <div id="divAdm" class="text-danger"></div>
                    </div>
                </div>
            </div>

        </div>
    </fieldset>
    <br />
    
    <fieldset title="Dados Pessoais do Funcionário" class=" text-info alert-info">

        <p>
            <button type="button" id="Novo" value="" class="btn btn-info" data-toggle="modal" data-target="#myModal" data-keyboard="false">Novo Endereço</button>
        </p>

        <div class="form-group">
            <div class="alert-success form-horizontal">
                <div class="col-sm-12">
                    <table id="tblEndereco" class="table">
                        <thead>
                            <tr class="ui-button-text">
                                <th>LOGRADOURO</th>
                                <th>NUM.</th>
                                <th>COMPLEMENTO</th>
                                <th>BAIRRO</th>
                                <th>CEP</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>

    </fieldset>

<!--INICIO MODAL -->
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog modal-lg">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header bg-info">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">FUNCIONÁRIO - ENDEREÇO</h4>
                </div>
                <div class="modal-body">

                    <div class="form-horizontal">

                        <div class="form-group">
                            <div class="col-sm-2">
                                ENDEREÇO
                            </div>
                            <div class="col-sm-6">
                               
                                <input type="text" id="LOGRADOURO" class="form-control" />
                                <div id="divLog" class="text-danger"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2">
                                NUM.
                            </div>
                            <div class="col-sm-6">
                                <input type="text" id="NUMLOGRADOURO" class="form-control" />

                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2">
                                COMPLEMENTO
                            </div>
                            <div class="col-sm-6">
                                <input type="text" id="COMPLEMENTO" class="form-control" />

                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2">
                                BAIRRO
                            </div>
                            <div class="col-sm-6">
                                <input type="text" id="BAIRRO" class="form-control" />

                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2">
                                CEP
                            </div>
                            <div class="col-sm-6">
                                <input type="text" id="CEP" class="form-control" autofocus="autofocus" autocomplete="on"/>

                            </div>
                        </div>


                    </div>
                </div>
                <div class="modal-footer">
                    <div class="form-group">
                        <div class="col-sm-6 text-center">
                            <button type="button" id="btnSalvarEndereco" class="btn btn-info" data-dismiss="modal">Salvar</button>
                        </div>
                        <div class="col-sm-6 text-center">
                            <button type="button" id="btnCancelarEndereco" class="btn btn-info" data-dismiss="modal">Cancelar</button>

                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
        <!--FIM MODAL-->
    <br />
   // @Html.Partial("_PartialEnderecoFuncionario", Model.TBEnderecos.ToList(), null)
    <div class="form-group">
        <div class="col-md-offset-2 col-sm-4">
            @Html.ActionLink("VOLTAR", "List", "Funcionario", null, new { @class = "btn btn-info" }) 
        </div>
        <div class="col-md-offset-2 col-sm-4">
            <input type="submit" id="btnSalvar" value="SALVAR" class="btn btn-info" alt="Salvar Tudo" />
        </div>
    </div>

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/css")
    @Scripts.Render("~/bundles/jquery.inputmask")

    <script src="~/Scripts/jquery.inputmask/jquery.inputmask.js"></script>
    <script src="~/Scripts/jquery.inputmask/jquery.inputmask.date.extensions.js"></script>
    <script src="~/Scripts/jquery.inputmask/jquery.inputmask.extensions.js"></script>
    <script src="~/Scripts/jquery.inputmask/jquery.inputmask.numeric.extensions.js"></script>
    <script src="~/Scripts/jquery.inputmask/jquery.inputmask.phone.extensions.js"></script>
    <script src="~/Scripts/jquery.inputmask/jquery.inputmask.regex.extensions.js"></script>
    <script src="~/Scripts/funcoes.js"></script>

    <script>
        $(document).ready(function () {

            $("#DTADMISSAO").inputmask("d/m/y", { "placeholder": "dd/mm/yyyy" });

            $("#NMFUNCIONARIO").change(function(){
                $("#divNom").empty();
            });
            
            $("#DTADMISSAO").change(function () {
                $("#divAdm").empty();
            });

            $("#LOGRADOURO").change(function () {
                $("#divLog").empty();
            });

            

            
            //SALVAR DADOS DO ENDEREÇO
            $("#btnSalvarEndereco").click(function () {

                //$('#confirm-delete').on('show.bs.modal', function (e) {
                //    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
                //});

                //$('#myModal').on('shown.bs.modal', function () {
                //    $('#LOGRADOURO').focus()
                //})
                var intFuncId = $("#TBFUNCIONARIOID").val();
                //alert(intFuncId);
                var strLogra = $("#LOGRADOURO").val();
                var strNum = $("#NUMLOGRADOURO").val();
                var strCom = $("#COMPLEMENTO").val();
                var strBai = $("#BAIRRO").val();
                var strCEP = $("#CEP").val();

                if (strLogra.length < 3) {

                    $("#divLog").html("* Campo Endereço é obrigatório !");
                    return false;
                };
                //alert(intFuncId + '\n' + strLogra + '\n' + strNum + '\n' + strBai + '\n' + strCEP + '\n' + strCom);

                //SALVA O ENDEREÇO DO FUNCIONÁRIO
                /*$.getJSON("/Endereco/Create/",
                    {
                        pLogradouro: strLogra,
                        pNumLogradouro: strNum,
                        pComplemento: strCom,
                        pBairro: strBai,
                        pCEP: strCEP,
                        pIDFunc: intFuncId
                    }
                    , function (data) {
                        var url = "/Administrativo/Funcionario/List/";
                        window.location.href = url;
                    }).success(function (data) {
                        alert("success");
                    }).error(function (data) {
                        alert("error");
                    }).complete(function (data) {
                        alert("complete");
                    });*/
                //FIM SALVA ENDEREÇO

                $("#tblEndereco > tbody").append(
                    "<tr>" +
                    "<th>" + $("#LOGRADOURO").val() + "</th>" +
                    "<th>" + $("#NUMLOGRADOURO").val() + "</th>" +
                    "<th>" + $("#COMPLEMENTO").val() + "</th>" +
                    "<th>" + $("#BAIRRO").val() + "</th>" +
                    "<th>" + $("#CEP").val() + "</th>" +
                    "<th>" + "<button type='button' id='excluir' value='' class='btn btn-sm btn-info' onclick='RemoveTableRow(this)'>Excluir</button>" +
                    "</tr>"
                    );

                



            });
            //$.fn.modal.Constructor.DEFAULTS.keyboard = false
            //$("#Novo").click(function () {
            //    $("#myModal").modal({ backdrop: "static" });
            //});

            //SALVAR DADOS PESSOAIS
            $("#btnSalvar").click(function () {
                //VALIDAR CAMPOS DE DADOS PESSOAIS
                if (($("#NMFUNCIONARIO").val().trim().length < 3) || ($("#DTADMISSAO").val().trim().length < 10)) {
                    if ($("#NMFUNCIONARIO").val().trim().length < 3) {
                        $("#divNom").html("* O Campo Nome do Funcionário é obrigatório !");
                        return false;
                    }

                    if ($("#DTADMISSAO").val().trim().length < 10) {
                        $("#divAdm").html("* O Campo Data de Admissão é obrigatório !");
                        return false;
                    }
                };
            });
        });

        //INÍCIO
        $('#CEP').change(function (e) {
            // alert('1');
            e.preventDefault();
            $('#LOGRADOURO').val('');
            $('#NUMLOGRADOURO').val('');
            $('#COMPLEMENTO').val('');
            $('#BAIRRO').val('');

            var cep = $('#CEP').val().replace("-", "");
            $.getJSON("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=json", {}, function (data) {
                if (data.resultado_txt == 'sucesso - cep completo') {
                    $('#LOGRADOURO').val(data.tipo_logradouro + ' ' + data.logradouro);
                    //$('#UF').val(data.uf);
                    //$('#Cidade').val(data.cidade);
                    $('#BAIRRO').val(data.bairro);

                };
            });

        });
        //FIM
    </script>
}

My question is how to send the data from TBFuncionario and TBEndereco to the Controller?

I've read some posts: Two models and a Controller , and even then I can not populate the TBE model and send them to the Controller.

How do I set the Address values in the TBD model?

    
asked by anonymous 16.08.2015 / 02:34

1 answer

2

You can create an intermediate class (view model), where you will have two attributes, one of type TBEndereco and TBFuncionario example:

public class CadastroViewModel
{
    public TBEndereco Endereco { get; set; }        
    public TBFuncionario Funcionario { get; set; }
}

Now pass this class on the model of your view, and then receive the same in your controller. To access the attributes in the view just do the normal process:

@model caminho.CadastroViewModel

@Html.EditorFor(model => model.Funcionario.DTADMISSAO)

I hope I have helped

    
16.08.2015 / 05:35