Datetime field problem in POST ASP.NET MVC

Asked

Viewed 587 times

0

Field Datetime getting 01/01/0001 00:00:00, and not with the date before the 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 Create GET I place 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 correctly opened when View Create.

inserir a descrição da imagem aqui

When I post and there is some error from another field, this field Datetime comes this way, 01/01/0001 00:00:00

    // POST: Pessoa/Create
    // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
    // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([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);
    }

inserir a descrição da imagem aqui

  • In your bind I see Datanascimento, but not Datacadastro.

  • Exactly Leandro, I just saw this, I changed my bind only to Exclude("Handle") which is my PK, because I had created the controller with my entityframework entity , then I deleted the views and created them with my models, and I forgot to change the Binds.

1 answer

1

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

change your property to the code below:

public DateTime? DataCadastro { get; set; }

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

So, after the return of a post, the field will remain blank.

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

Browser other questions tagged

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