How to register legal and physical persons in c# mvc?

Asked

Viewed 1,001 times

3

How I do in Personal Action Create?

Personal:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PessoaId,Telefone,Endereco,CEP,Cidade,Estado,Habilitado,Nome,CPF,DataNascimento,Profissao,EstadoCivil,Pontos,NomeFantasia,RazaoSocial,CNPJ,TelComercial,DataAbertura")] Pessoa pessoa)
{
    if (ModelState.IsValid)
    {
        db.Pessoas.Add(pessoa);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(pessoa);         
}

Views/People/Create:

 @model PraticarEsportes.Models.ViewModel
    @Scripts.Render("~/bundles/jquery")

    @{
        ViewBag.Title = "Cadastro de Usuário";
    }

    <h2>Cadastro de Usuário</h2>

    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">

            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.Pessoa.Telefone, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Pessoa.Telefone, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Pessoa.Telefone, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Pessoa.Endereco, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Pessoa.Endereco, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Pessoa.Endereco, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Pessoa.CEP, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Pessoa.CEP, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Pessoa.CEP, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Pessoa.Cidade, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Pessoa.Cidade, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Pessoa.Cidade, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Pessoa.Estado, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Pessoa.Estado, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Pessoa.Estado, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Física (Praticante): Nome -->
            <div class="Nome">
                @Html.LabelFor(model => model.Praticante.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Praticante.Nome, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Praticante.Nome, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Física (Praticante): CPF -->
            <div class="CPF">
                @Html.LabelFor(model => model.Praticante.CPF, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Praticante.CPF, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Praticante.CPF, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Física (Praticante): DataNascimento -->
            <div class="DataNascimento">
                @Html.LabelFor(model => model.Praticante.DataNascimento, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Praticante.DataNascimento, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Praticante.DataNascimento, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Física (Praticante): Profissao -->
            <div class="Profissao">
                @Html.LabelFor(model => model.Praticante.Profissao, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Praticante.Profissao, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Praticante.Profissao, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Física (Praticante): EstadoCivil -->
            <div class="EstadoCivil">
                @Html.LabelFor(model => model.Praticante.EstadoCivil, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Praticante.EstadoCivil, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Praticante.EstadoCivil, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Física (Praticante): Pontos -->
            <div class="Pontos">
                @Html.LabelFor(model => model.Praticante.Pontos, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Praticante.Pontos, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Praticante.Pontos, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Jurídica (Estabelecimento): NomeFantasia -->
            <div class="NomeFantasia">
                @Html.LabelFor(model => model.Estabelecimento.NomeFantasia, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Estabelecimento.NomeFantasia, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Estabelecimento.NomeFantasia, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Jurídica (Estabelecimento): RazaoSocial -->
            <div class="RazaoSocial">
                @Html.LabelFor(model => model.Estabelecimento.RazaoSocial, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Estabelecimento.RazaoSocial, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Estabelecimento.RazaoSocial, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Jurídica (Estabelecimento): CNPJ -->
            <div class="CNPJ">
                @Html.LabelFor(model => model.Estabelecimento.CNPJ, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Estabelecimento.CNPJ, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Estabelecimento.CNPJ, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Jurídica (Estabelecimento): TelComercial -->
            <div class="TelComercial">
                @Html.LabelFor(model => model.Estabelecimento.TelComercial, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Estabelecimento.TelComercial, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Estabelecimento.TelComercial, "", new { @class = "text-danger" })
                </div>
            </div>

            <!-- Pessoa Jurídica (Estabelecimento): DataAbertura -->
            <div class="DataAbertura" id="DataAberturaId">
                @Html.LabelFor(model => model.Estabelecimento.DataAbertura, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Estabelecimento.DataAbertura, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Estabelecimento.DataAbertura, "", new { @class = "text-danger" })
                </div>
            </div>    

            <!-- Radio button para selecionar pessoa física ou jurídica -->
            <div>
                <input id="pessoaFisicaId" type="radio" name="tipoPessoa" value="pessoaFisica" onClick="habilitaCampo(this.id)"/>Pessoa Física
                <input id="pessoaJuridicaId" type="radio" name="tipoPessoa" value="pessoaJuridica" onClick="habilitaCampo(this.id)"/>Pessoa Jurídica
            </div>

            <script type="text/javascript">
                $(document).ready(function () {
                    // Oculta os atributos da pessoa física
                    $(".Nome").hide();
                    $(".CPF").hide();
                    $(".DataNascimento").hide();
                    $(".Profissao").hide();
                    $(".EstadoCivil").hide();
                    $(".Pontos").hide();
                    // Oculta os atributos da pessoa jurídica
                    $(".NomeFantasia").hide();
                    $(".RazaoSocial").hide();
                    $(".CNPJ").hide();
                    $(".TelComercial").hide();
                    $(".DataAbertura").hide();


                    $("input[name=tipoPessoa]").on("click", function () {
                        // Se pessoa física estiver selecionado
                        if (pessoaFisicaId.checked) {
                            // Exibe os atributos da pessoa física
                            $(".Nome").show();
                            $(".CPF").show();
                            $(".DataNascimento").show();
                            $(".Profissao").show();
                            $(".EstadoCivil").show();
                            $(".Pontos").show();
                            // Oculta os atributos da pessoa jurídica
                            $(".NomeFantasia").hide();
                            $(".RazaoSocial").hide();
                            $(".CNPJ").hide();
                            $(".TelComercial").hide();
                            $(".DataAbertura").hide();
                        }

                        // Se pessoa jurídica estiver selecionado
                        else if (pessoaJuridicaId.checked) {
                            // Exibe os atributos da pessoa jurídica
                            $(".NomeFantasia").show();
                            $(".RazaoSocial").show();
                            $(".CNPJ").show();
                            $(".TelComercial").show();
                            $(".DataAbertura").show();
                            // Oculta os atributos da pessoa física
                            $(".Nome").hide();
                            $(".CPF").hide();
                            $(".DataNascimento").hide();
                            $(".Profissao").hide();
                            $(".EstadoCivil").hide();
                            $(".Pontos").hide();
                        }

                    });
                });
            </script>

        <!-- Botão Salvar -->
        <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type = "submit" value="Salvar" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <!-- Botão voltar para lista -->
    <div>
        @*@Html.ActionLink("Back to List", "Index")*@
        <a href='@Url.Action("Index", "Pessoas")'>
            <img src='@Url.Content("~/Content/img/voltar.png")' class="botaoicone" title="Voltar" /> Lista de Usuários
        </a>
    </div>
   <!-- --> 


     @section scripts{
            <script>
                $(function () {
                    $('input, select, textarea').each(function () {
                        if ($(this).hasClass('input-validation-error'))
                        $(this).focus();
                    });
                });
            </script>
        }

Classe Pessoa:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PraticarEsportes.Models
{
    public class Pessoa
    {
        [Key]
        public int PessoaId { get; set; }

        [Required(ErrorMessage = "Preencha o telefone")]
        [DisplayName("Telefone")]
        [DataType(DataType.PhoneNumber)]
        public string Telefone { get; set; }

        [Required(ErrorMessage = "Preencha o endereço")]
        [DisplayName("Endereço")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O endereço deve ter entre 3 e 255 caracteres.")]
        public string Endereco { get; set; }

        [Required(ErrorMessage = "Preencha o CEP")]
        [DisplayName("CEP")]
        [ValidaCEP]
        public string CEP { get; set; }

        [Required(ErrorMessage = "Preencha a cidade")]
        [DisplayName("Cidade")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "A cidade deve ter entre 3 e 255 caracteres.")]
        public string Cidade { get; set; }

        [Required(ErrorMessage = "Preencha o estado")]
        [DisplayName("Estado")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O estado deve ter entre 3 e 255 caracteres.")]
        public string Estado { get; set; }

        [Required(ErrorMessage = "Preencha o email")]
        [DisplayName("Email")]
        [DataType(DataType.EmailAddress)]
        [EmailAddress(ErrorMessage = "E-mail inválido")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O email deve ter entre 3 e 255 caracteres.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Preencha a senha")]
        [DisplayName("Senha")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "A senha deve ter entre 3 e 50 caracteres.")]
        [DataType(DataType.Password)]
        public string Senha { get; set; }

        [DisplayName("Habilitado")]
        public bool Habilitado { get; set; }

        public virtual ICollection<Checkin> Checkins { get; set; }
    }
}

Practicing Class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using PraticarEsportes.Models;

namespace PraticarEsportes.Models
{
    public class Praticante : Pessoa
    {
        [Required(ErrorMessage = "Preencha o nome")]
        [DisplayName("Nome")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O nome deve ter entre 3 e 255 caracteres.")]
        public string Nome { get; set; }

        [Required(ErrorMessage = "Preencha o CPF")]
        [DisplayName("CPF")]
        [ValidaCPF]
        public string CPF { get; set; }

        [DisplayName("Data de Nascimento")]
        [DataType(DataType.DateTime, ErrorMessage = "Formato de data inválido")]
        [ScaffoldColumn(false)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss tt}")]
        public DateTime DataNascimento { get; set; }

        [Required(ErrorMessage = "Preencha a profissão")]
        [DisplayName("Profissão")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "A profissão deve ter entre 3 e 255 caracteres.")]
        public string Profissao { get; set; }

        [Required(ErrorMessage = "Preencha o estado civil")]
        [DisplayName("Estado Civil")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O estado civil deve ter entre 3 e 255 caracteres.")]
        public string EstadoCivil { get; set; }

        [DisplayName("Pontos")]
        public int Pontos { get; set; }

    }
}

Class Establishment:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PraticarEsportes.Models
{
    public class Estabelecimento : Pessoa
    {
        [Required(ErrorMessage = "Preencha o nome fantasia")]
        [DisplayName("Nome Fantasia")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O nome fantasia deve ter entre 3 e 255 caracteres.")]
        public string NomeFantasia { get; set; }

        [Required(ErrorMessage = "Preencha a razão social")]
        [DisplayName("Razão Social")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "A razão social deve ter entre 3 e 255 caracteres.")]
        public string RazaoSocial { get; set; }

        [Required(ErrorMessage = "Preencha o CNPJ")]
        [DisplayName("CNPJ")]
        [ValidaCNPJ]
        public string CNPJ { get; set; }

        [Required(ErrorMessage = "Preencha o telefone comercial")]
        [DisplayName("Telefone Comercial")]
        [DataType(DataType.PhoneNumber)]
        public string TelComercial { get; set; }

        [DisplayName("Data de Abertura")]
        [DataType(DataType.DateTime, ErrorMessage = "Formato de data inválido")]
        [ScaffoldColumn(false)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss tt}")]
        public DateTime DataAbertura { get; set; }

    }
}
  • What’s your question? Give more context to what you’re doing.

  • In Action Create you are only saving the attributes of the Person class, but I need you to also save those of the Practitioner and Establishment class that are inherited from the Person class

  • Attributes class Person: Personal, Telephone, Address, Zip code, City, State, Enabled Attributes class Practitioner: Name, CPF, Birth date, Profession, Statevil, Points Attributes class Establishment: NomeFantasia,RazaoSocial,CNPJ,TelComercial,DataAbertura

  • Can you please update your question with the definition of Models? The same code.

  • I put the class codes

1 answer

1


The point is that you are using the same screen to register both a Praticante as to a Estabelecimento, which can make your logic very complicated. The best would be to have two screens: one for registration of Practitioners, another for registration of Establishments.

Anyway, you can leave everything on the same screen, but the correct thing would be to generate a Viewmodel with the data of the three classes: Pessoa, Praticante and Estabelecimento:

namespace PraticarEsportes.ViewModels
{
    public class PessoaViewModel
    {
        // Deixe PessoaId apenas se for fazer a edição da mesma forma.
        public int PessoaId { get; set; }

        [Required(ErrorMessage = "Preencha o telefone")]
        [DisplayName("Telefone")]
        [DataType(DataType.PhoneNumber)]
        public string Telefone { get; set; }

        [Required(ErrorMessage = "Preencha o endereço")]
        [DisplayName("Endereço")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O endereço deve ter entre 3 e 255 caracteres.")]
        public string Endereco { get; set; }

        [Required(ErrorMessage = "Preencha o CEP")]
        [DisplayName("CEP")]
        [ValidaCEP]
        public string CEP { get; set; }

        [Required(ErrorMessage = "Preencha a cidade")]
        [DisplayName("Cidade")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "A cidade deve ter entre 3 e 255 caracteres.")]
        public string Cidade { get; set; }

        [Required(ErrorMessage = "Preencha o estado")]
        [DisplayName("Estado")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O estado deve ter entre 3 e 255 caracteres.")]
        public string Estado { get; set; }

        [Required(ErrorMessage = "Preencha o email")]
        [DisplayName("Email")]
        [DataType(DataType.EmailAddress)]
        [EmailAddress(ErrorMessage = "E-mail inválido")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O email deve ter entre 3 e 255 caracteres.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Preencha a senha")]
        [DisplayName("Senha")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "A senha deve ter entre 3 e 50 caracteres.")]
        [DataType(DataType.Password)]
        public string Senha { get; set; }

        [DisplayName("Habilitado")]
        public bool Habilitado { get; set; }

        /* Campos de Praticante */
        [Required(ErrorMessage = "Preencha o nome")]
        [DisplayName("Nome")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O nome deve ter entre 3 e 255 caracteres.")]
        public string Nome { get; set; }

        [Required(ErrorMessage = "Preencha o CPF")]
        [DisplayName("CPF")]
        [ValidaCPF]
        public string CPF { get; set; }

        [DisplayName("Data de Nascimento")]
        [DataType(DataType.DateTime, ErrorMessage = "Formato de data inválido")]
        [ScaffoldColumn(false)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss tt}")]
        public DateTime DataNascimento { get; set; }

        [Required(ErrorMessage = "Preencha a profissão")]
        [DisplayName("Profissão")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "A profissão deve ter entre 3 e 255 caracteres.")]
        public string Profissao { get; set; }

        [Required(ErrorMessage = "Preencha o estado civil")]
        [DisplayName("Estado Civil")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O estado civil deve ter entre 3 e 255 caracteres.")]
        public string EstadoCivil { get; set; }

        [DisplayName("Pontos")]
        public int Pontos { get; set; }

        /* Campos de Estabelecimento */
        [Required(ErrorMessage = "Preencha o nome fantasia")]
        [DisplayName("Nome Fantasia")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "O nome fantasia deve ter entre 3 e 255 caracteres.")]
        public string NomeFantasia { get; set; }

        [Required(ErrorMessage = "Preencha a razão social")]
        [DisplayName("Razão Social")]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "A razão social deve ter entre 3 e 255 caracteres.")]
        public string RazaoSocial { get; set; }

        [Required(ErrorMessage = "Preencha o CNPJ")]
        [DisplayName("CNPJ")]
        [ValidaCNPJ]
        public string CNPJ { get; set; }

        [Required(ErrorMessage = "Preencha o telefone comercial")]
        [DisplayName("Telefone Comercial")]
        [DataType(DataType.PhoneNumber)]
        public string TelComercial { get; set; }

        [DisplayName("Data de Abertura")]
        [DataType(DataType.DateTime, ErrorMessage = "Formato de data inválido")]
        [ScaffoldColumn(false)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss tt}")]
        public DateTime DataAbertura { get; set; }

        public TipoPessoa TipoPessoa { get; set; }
    }
}

Your View Create, so it would look like this:

@model PraticarEsportes.ViewModels.PessoaViewModel
@* Não faça render de Scripts aqui. Use _Layout ou @section Scripts *@
@* Scripts.Render("~/bundles/jquery") *@

@{
    ViewBag.Title = "Cadastro de Usuário";
}

<h2>Cadastro de Usuário</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.Pessoa.Telefone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Pessoa.Telefone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Pessoa.Telefone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Pessoa.Endereco, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Pessoa.Endereco, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Pessoa.Endereco, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Pessoa.CEP, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Pessoa.CEP, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Pessoa.CEP, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Pessoa.Cidade, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Pessoa.Cidade, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Pessoa.Cidade, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Pessoa.Estado, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Pessoa.Estado, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Pessoa.Estado, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Física (Praticante): Nome -->
        <div class="Nome">
            @Html.LabelFor(model => model.Praticante.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Praticante.Nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Praticante.Nome, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Física (Praticante): CPF -->
        <div class="CPF">
            @Html.LabelFor(model => model.Praticante.CPF, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Praticante.CPF, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Praticante.CPF, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Física (Praticante): DataNascimento -->
        <div class="DataNascimento">
            @Html.LabelFor(model => model.Praticante.DataNascimento, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Praticante.DataNascimento, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Praticante.DataNascimento, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Física (Praticante): Profissao -->
        <div class="Profissao">
            @Html.LabelFor(model => model.Praticante.Profissao, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Praticante.Profissao, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Praticante.Profissao, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Física (Praticante): EstadoCivil -->
        <div class="EstadoCivil">
            @Html.LabelFor(model => model.Praticante.EstadoCivil, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Praticante.EstadoCivil, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Praticante.EstadoCivil, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Física (Praticante): Pontos -->
        <div class="Pontos">
            @Html.LabelFor(model => model.Praticante.Pontos, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Praticante.Pontos, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Praticante.Pontos, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Jurídica (Estabelecimento): NomeFantasia -->
        <div class="NomeFantasia">
            @Html.LabelFor(model => model.Estabelecimento.NomeFantasia, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Estabelecimento.NomeFantasia, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Estabelecimento.NomeFantasia, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Jurídica (Estabelecimento): RazaoSocial -->
        <div class="RazaoSocial">
            @Html.LabelFor(model => model.Estabelecimento.RazaoSocial, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Estabelecimento.RazaoSocial, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Estabelecimento.RazaoSocial, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Jurídica (Estabelecimento): CNPJ -->
        <div class="CNPJ">
            @Html.LabelFor(model => model.Estabelecimento.CNPJ, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Estabelecimento.CNPJ, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Estabelecimento.CNPJ, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Jurídica (Estabelecimento): TelComercial -->
        <div class="TelComercial">
            @Html.LabelFor(model => model.Estabelecimento.TelComercial, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Estabelecimento.TelComercial, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Estabelecimento.TelComercial, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- Pessoa Jurídica (Estabelecimento): DataAbertura -->
        <div class="DataAbertura" id="DataAberturaId">
            @Html.LabelFor(model => model.Estabelecimento.DataAbertura, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Estabelecimento.DataAbertura, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Estabelecimento.DataAbertura, "", new { @class = "text-danger" })
            </div>
        </div>    

        <!-- Radio button para selecionar pessoa física ou jurídica -->
        <div>
            <label>
                @Html.RadioButtonFor(model => model.TipoPessoa, TipoPessoa.Fisica, new { onclick = "habilitaCampo('pessoaFisicaId')" }) Física
            </label>
            <label>
                @Html.RadioButtonFor(model => model.TipoPessoa, TipoPessoa.Juridica, new { onclick = "habilitaCampo('pessoaJuridicaId')" }) Jurídica
            </label>
        </div>

        <script type="text/javascript">
            $(document).ready(function () {
                // Oculta os atributos da pessoa física
                $(".Nome").hide();
                $(".CPF").hide();
                $(".DataNascimento").hide();
                $(".Profissao").hide();
                $(".EstadoCivil").hide();
                $(".Pontos").hide();
                // Oculta os atributos da pessoa jurídica
                $(".NomeFantasia").hide();
                $(".RazaoSocial").hide();
                $(".CNPJ").hide();
                $(".TelComercial").hide();
                $(".DataAbertura").hide();


                $("input[name=tipoPessoa]").on("click", function () {
                    // Se pessoa física estiver selecionado
                    if (pessoaFisicaId.checked) {
                        // Exibe os atributos da pessoa física
                        $(".Nome").show();
                        $(".CPF").show();
                        $(".DataNascimento").show();
                        $(".Profissao").show();
                        $(".EstadoCivil").show();
                        $(".Pontos").show();
                        // Oculta os atributos da pessoa jurídica
                        $(".NomeFantasia").hide();
                        $(".RazaoSocial").hide();
                        $(".CNPJ").hide();
                        $(".TelComercial").hide();
                        $(".DataAbertura").hide();
                    }

                    // Se pessoa jurídica estiver selecionado
                    else if (pessoaJuridicaId.checked) {
                        // Exibe os atributos da pessoa jurídica
                        $(".NomeFantasia").show();
                        $(".RazaoSocial").show();
                        $(".CNPJ").show();
                        $(".TelComercial").show();
                        $(".DataAbertura").show();
                        // Oculta os atributos da pessoa física
                        $(".Nome").hide();
                        $(".CPF").hide();
                        $(".DataNascimento").hide();
                        $(".Profissao").hide();
                        $(".EstadoCivil").hide();
                        $(".Pontos").hide();
                    }

                });
            });
        </script>

    <!-- Botão Salvar -->
    <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type = "submit" value="Salvar" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<!-- Botão voltar para lista -->
<div>
    @*@Html.ActionLink("Back to List", "Index")*@
    <a href='@Url.Action("Index", "Pessoas")'>
        <img src='@Url.Content("~/Content/img/voltar.png")' class="botaoicone" title="Voltar" /> Lista de Usuários
    </a>
</div>

A detail here: notice that I modified the Person’s choice field to support Enums:

        <!-- Radio button para selecionar pessoa física ou jurídica -->
        <div>
            <label>
                @Html.RadioButtonFor(model => model.TipoPessoa, TipoPessoa.Fisica, new { onclick = "habilitaCampo('pessoaFisicaId')" }) Física
            </label>
            <label>
                @Html.RadioButtonFor(model => model.TipoPessoa, TipoPessoa.Juridica, new { onclick = "habilitaCampo('pessoaJuridicaId')" }) Jurídica
            </label>
        </div>

TipoPessoa, therefore needs to be defined:

public enum TipoPessoa
{
    Fisica,
    Juridica
}

The Controller will then receive the Viewmodel:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PessoaViewModel pessoaViewModel)
{
    ...        
}

Notice I no longer need Bind. Bind is useful when using a Model, not a Viewmodel. It serves to prevent some things from being inserted into the bank improperly. Therefore, we need to implement the method to solve what we are inserting.

To enter the missing data, the instance to be entered must be the derivative entity of Pessoa: Or a Praticante, or a Estabelecimento. Pessoa is not a good to insert.

So the method stays like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PessoaViewModel pessoaViewModel)
{
    if (ModelState.IsValid)
    {
        if (pessoasViewModel.TipoPessoa == TipoPessoa.Fisica) 
        {
            var praticante = new Praticante
            {
                Telefone = pessoaViewModel.Telefone,
                Endereco = pessoaViewModel.Endereco,
                CEP = pessoaViewModel.CEP,
                Cidade = pessoaViewModel.Cidade,
                Estado = pessoaViewModel.Estado,
                Email = pessoaViewModel.Email,
                Senha = pessoaViewModel.Senha,
                Habilitado = pessoaViewModel.Habilitado,
                Nome = pessoaViewModel.Nome,
                CPF = pessoaViewModel.CPF,
                Profissao = pessoaViewModel.Profissao,
                EstadoCivil = pessoaViewModel.EstadoCivil,
                Pontos = pessoaViewModel.Pontos
            };

            db.Praticantes.Add(praticante);
        } else 
        { 
            var estabelecimento = new Estabelecimento 
            {
                Telefone = pessoaViewModel.Telefone,
                Endereco = pessoaViewModel.Endereco,
                CEP = pessoaViewModel.CEP,
                Cidade = pessoaViewModel.Cidade,
                Estado = pessoaViewModel.Estado,
                Email = pessoaViewModel.Email,
                Senha = pessoaViewModel.Senha,
                Habilitado = pessoaViewModel.Habilitado,
                NomeFantasia = pessoaViewModel.NomeFantasia,
                RazaoSocial = pessoaViewModel.RazaoSocial,
                CNPJ = pessoaViewModel.CNPJ,
                TelComercial = pessoaViewModel.TelComercial,
                DataAbertura = pessoaViewModel.DataAbertura
            };

            db.Estabelecimentos.Add(estabelecimento);
        }

        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(pessoaViewModel);         
}

One last detail: make sure that Praticantes and Estabelecimentos sane DbSet<Praticante> and DbSet<Estabelecimento> in your data context.

  • Where will the type be defined? And one more question, could not have a class (e.g., Viewmodel) with public Pessoa Pessoa { get; set; } public Practitioner { get; set; } public Establishment Establishment { get; set; } to take the fields of the Pessoa classes, Practitioner and Establishment instead of putting all fields?

  • About the TipoPessoa, usually define in the namespace in MeuProjeto.Enums (enums directory). About dividing the Viewmodel, not only is it bad practice but it is incorrect. A Pessoa, by its modeling, can not be Praticante and Estabelecimento at the same time. This would only make sense if their modeling were a composition, and not an inheritance, which is not the case, because a Pessoa can’t be Praticante and Estabalecimento at the same time.

  • It worked!!! Thank you.

  • @Grazianetavares See here how to use the site. Need more help, just say the word.

Browser other questions tagged

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