C# – Populate EditorFor for DateTime

asp.net-mvcasp.net-mvc-4cnetrazor

I have the following model for a person:

public class Person
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Id")]
    public int Id { get; set; }

    [Display(Name = "Name")]
    [StringLength(30)]
    public string Name { get; set; }

    [Display(Name = "Last Name")]
    [StringLength(30)]
    public string LastName { get; set; }

    [Display(Name = "Birth date")]
    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }

    [Display(Name = "Height")]
    [Range(120,250, ErrorMessage="Wrong height!")]
    public int Height { get; set; }
}

When I create a new Person, it creates normally in database with the following date format for BirthDate: dd.mm.yyyy

The problem is when I try to edit details of that person, birth date is not displayed inside EditorFor field. All other details like name, last name and height are displayed but birth date not.

So, this all displays all saved values correctly:

@Html.EditorFor(model => model.Person.Name)
@Html.EditorFor(model => model.Person.LastName)
@Html.EditorFor(model => model.Person.Height)

But this doesn't display anything or in some browsers it displays just date format without values:

@Html.EditorFor(model => model.Person.BirthDate)

When I look at the source code of the web site, I can see there is a value which represents a date. It's just not displayed. I also tried to populate it with javascript but without success. Any ideas?

Thank you!

Best Answer

Look at this question: MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in IE

One of possible solutions:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]