Luke Hutton
Luke Hutton

Reputation: 10722

DateTime property not set properly on View Model

When my form with the view below is being posted to my controller action MyAction, I get a 1/1/0001 12:00:00 AM date on my StartDate property, the format of the date coming in should be dd/MM/yyyy. I set it to 14/04/2011 on the form but it comes in 1/1/0001. Is there some culture or setting I'm not configuring properly?

In my controller, culture is set to

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-AU"); 

Action posted to:

[HttpPost]
public ActionResult MyAction(MyViewModel myViewModel)
{            
    if (!ModelState.IsValid) return View("Index", myViewModel);
    ...

View Model:

public class MyViewModel 
{
    [DataType(DataType.Date)]
    [DisplayName("Start Date")]
    [Required]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime StartDate { get; set; }
}

On View:

<%=Html.EditorFor(m => m.StartDate, new { style = "width: 110px;", @class = "date" })%>

Upvotes: 2

Views: 1293

Answers (1)

Luke Hutton
Luke Hutton

Reputation: 10722

My bad, I wasn't setting Thread.CurrentThread.CurrentCulture in MyAction, only in the Index action. I moved the logic into a BaseController class that all the controllers extend.

Upvotes: 0

Related Questions