Individual and Legal in the same table

Asked

Viewed 182 times

3

Could you help me please ?

I am developing a crud for client, where I will leave physical and legal person in the same table, but in 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 mandatory will be:

Natural Person: Name

Legal Entity: Social Reason.

As the structure is part of the same form, and the fields name and razaoSocial are obligatory, I need to fill out the two fields regardless of whether the client is physical or legal, so I would like to know how I can get 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);
    }
  • you want to keep the required, but whether it is a legal or a natural person, that is?

  • Exactly Ricardo, but as the two camps are required required to fill in both fields in order to submit the form.

  • It would be good for you to post the AddClientViewModels to see the structure. Another point is that it makes no sense to keep the Required when in fact, they are not.

  • If you want to keep the required, need to write a class to validate the Model by checking whether it is physical or legal. This is done by implementing the interface IValidatableObject, which is actually quite simple

  • Fernando thanks for the reply, is that in the case if the client is Nome is required, if he is Legal a RazaoSocial is required, I have already arranged the question as per the request.

  • You can create the 2 Personal and Personal Entities by mapping the Entityframework to the same table each with their respective properties. At the time of the post of the data you choose which action will send the data according to the radio button.

  • Ricardo Potual, if you could give me an example ?

  • Yes, I set an example for you to understand how it works.

  • Ricardo his answer was perfect

Show 4 more comments

1 answer

3


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

// 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

Browser other questions tagged

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