Problem with DateTime field in ASP.NET MVC POST

0

DateTime field getting 01/01/0001 00:00:00, not the date before POST.

  

DataTime Field with DataAnnotations (MODEL)

    [Required(ErrorMessage = "Campo Data de cadastro é obrigatório.")]
    [Display(Name = "Data cadastro")]        
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}", ApplyFormatInEditMode = true)]
    [DataType(DataType.DateTime)]
    public DateTime DataCadastro { get; set; }
  

In the Create GET I put the current date in the field.

    public ActionResult Create()
    {
        PessoaModel pessoaModel = new PessoaModel();
        pessoaModel.Ativo = true;
        pessoaModel.DataCadastro = DateTime.Now;
        pessoaModel.UsuarioCadastro = "NICOLA BOGAR";

        return View(pessoaModel);
    }
  

DataTime field is set correctly when opening the Create View.

  

WhenIrunthepostandhavesomeerrorfromanotherfield,thisDateTimefieldcomesinthisway,01/01/000100:00:00

//POST:Pessoa/Create//Paraseprotegerdemaisataques,ativeaspropriedadesespecíficasaquevocêquerseconectar.Para//obtermaisdetalhes,consultehttps://go.microsoft.com/fwlink/?LinkId=317598.[HttpPost][ValidateAntiForgeryToken]publicActionResultCreate([Bind(Include="Handle,Ativo,TipoPessoa,CategoriaPessoa,Nome,CPF,RG,DataNascimento,CNPJ,IE,RazaoSocial,Sexo,EstadoCivil,Nacionalidade,EnderecoHandle,Contato,Auditoria")] PessoaModel pessoaModel)
    {
        if (ModelState.IsValid)
        {
            Pessoa pessoa = mapper.ToModelForEntity(pessoaModel);

            db.Pessoas.Add(pessoa);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(pessoaModel);
    }

    
asked by anonymous 20.10.2017 / 16:32

1 answer

1

This should occur due to the fact that your property is not nullable

change your ownership to the code below:

public DateTime? DataCadastro { get; set; }

In this way, your property may receive null values, ie when this date is not filled the property will be null.

So, after a post has returned, the field will remain blank.

When the property is not nullable , the DateTime, because it is not null, will default to "01/01/0001 00:00:00" in your codebehind, when it is not filled, causing this effect described by you.

    
20.10.2017 / 17:05