Physical and Legal Person on the same table

2

Could you help me please?

I am developing a client crud, where I will leave legal and physical person in the same table, but in the case when the user chooses the type of person through a radio button, I will show and hide some fields through javascript, and the only fields that will be required will be:

Individual: Name

Legal Entity: Corporate Name.

As the structure is part of the same form, and the fields name and reasonsocial are mandatory, I need to fill in both fields regardless of whether the client is physical or legal, so I would like to know how I can work around this problem.

AddClientViewModels:

 public class ApplicationClient
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    [Display(Name = "Tipo Pessoa")]
    public int TipoPessoa { get; set; }

    [Required(ErrorMessage = "Nome é obrigatório", AllowEmptyStrings = false)]
    [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Nome")]
    public String Nome { get; set; }

    [Required(ErrorMessage = "Razão Social é obrigatório", AllowEmptyStrings = false)]
    [StringLength(100, ErrorMessage = "A {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Razão Social")]
    public String RazaoSocial { get; set; }
 }

Controller:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Add(AddClientViewModels model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Não é possível carregar o usuário com o ID '{_userManager.GetUserId(User)}'.");
            }

            var client = new ApplicationClient { TipoPessoa = model.TypePerson,Nome = model.Name,
                                                 RazaoSocial = model.CompanyName
            };

            var result = await _clientManager.CreateClientAsync(client);

            TempData["MensagemSucesso"] = "Cliente cadastrado com sucesso";

            return View("Index");
        }

        return View(model);
    }
    
asked by anonymous 18.09.2018 / 19:34

1 answer

2

Here's an example of how you can change your model and implement the Validate method:

// adicione a interface IValidatableObject
public class ApplicationClient: IValidatableObject
{
    [Key]
    public Guid Id { get; set; }

    [Display(Name = "Tipo Pessoa")]
    public int TipoPessoa { get; set; }

    [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Nome")]
    public String Nome { get; set; }

    [StringLength(100, ErrorMessage = "A {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Razão Social")]
    public String RazaoSocial { get; set; }

    // implemente o método Validate
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (TipoPessoa == 1 && String.IsNullOrEmpty(Nome)) // supondo física
            yield return new ValidationResult("Nome é obrigatório", new [] { nameof(Nome) });

        if (TipoPessoa == 2 && String.IsNullOrEmpty(RazaoSocial)) // supondo jurídica
            yield return new ValidationResult("Razão Social é obrigatório", new [] { nameof(RazaoSocial) });
    }
}

When using yield return you are returning a validation error for your Model, which will be displayed in html

    
18.09.2018 / 20:00