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);
}