Modelstate invalida

Asked

Viewed 62 times

0

I have a class called, Colaborador. and the collaborator has a bank.

 public class Colaborador
 {
  public virtual Banco Banco { get; set; }
  public Guid? BancoId { get; set; }
 }

my problem, is that even though the bank is optional, invalidates the modelState, because some fields of the Bank class, are mandatory.

I tried to do so:

if (colaboradorViewModel.Banco.NomeDoBanco == null)
            {
                colaboradorViewModel.Banco = null;
            }

            if (!ModelState.IsValid)
            {
                ViewBag.Estado = new SelectList(_estadoAppService.ObterTodos(), "EstadoId", "Uf");
                ViewBag.Usuarios = new SelectList(_usuarioAppService.ObterTodos(), "UsuarioId", "Nome");
                return View(colaboradorViewModel);
            }

even so, it keeps validating the attributes of the object banco. how do I fix it??

My Collaboratordoconfi, it’s like this::

public class ColaboradorConfig: EntityTypeConfiguration<Colaborador>
    {
        public ColaboradorConfig()
        {
            ToTable("Colaboradores");
            HasKey(c => c.ColaboradorId);

            HasOptional(c => c.Banco).WithMany().HasForeignKey(b => b.BancoId);

        }
    }

Banco Config:

   public class BancoConfig: EntityTypeConfiguration<Banco>
    {
        public BancoConfig()
        {
            ToTable("Bancos");
            HasKey(b => b.IdBanco);
            Property(b => b.NomeDoBanco).HasMaxLength(50).IsRequired();
            Property(b => b.Agencia).HasMaxLength(10).IsRequired();
            Property(b => b.Conta).HasMaxLength(10).IsRequired();
            Property(b => b.DigitoAgencia).IsOptional();
            Property(b => b.Digito).IsOptional();
            Property(b => b.Op).IsOptional();
        }
    }
  • How is the bank mapping? Give an Inspect in Modelstate to see the errors and also put the print la in the question =)

  • I’ll edit the question, and put the config

  • How is the Bancoconfig?

  • edited the question and posted the bancoConfig

  • Man, how weird... if you inspect the Modelstate it gives you some message?

  • not of the error, it only of the invalidity! , does not validate, because the proprienty of the bank class, is obirgatorial.

  • face, give a select on the errors and send it to us +/- like this : var errors = Modelstate . Where(x => x.Value.Errors.Count > 0) . Select(x => new { x.Key, x.Value.Errors }) . Toarray();

  • As I told you, not the error, only the false, in modelState, because the attributes Name, agency and bank account are required.

  • Put all controller and view methods

Show 5 more comments
No answers

Browser other questions tagged

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