Question

after recently upgrading from MVC3 to 4 I am having some issues with datetimes. I display a date property like this:

<%: Html.DisplayFor(m => m.InvoiceDate, "datetime")%>&nbsp; 

"datetime" is a display template which looks like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<%: Model.HasValue ? Model.Value.ToString("dd/MM/yy", null) : ""%>

In my global.asax file I register the following model binders:

 ModelBinders.Binders.Add(typeof(DateTime), new SMEEDI.Portal.Common.DateTimeModelBinder());
 ModelBinders.Binders.Add(typeof(DateTime?), new SMEEDI.Portal.Common.DateTimeModelBinder());

Which look like this:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        if (String.IsNullOrEmpty(date))
            return null;

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));

        try
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-NZ");
            return DateTime.Parse(date, CultureInfo.CurrentCulture.DateTimeFormat);
        }

        catch (Exception)
        {

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));

            return null;

        }

The date time is displayed properly in the view, but when the form is submitted the date comes back like this: "7/20/2013 12:00:00 AM" and the DateTimeModelBinder throws a Format Exception: String was not recognized as a valid DateTime. (the month and day are the other way around in New Zealand).

Why does it come back in this format? Why can it not parse it? Why did this happen when upgrading to MVC 4? How can I get it to return in NZ format? Should I rather not specify the culture when parsing, was this something that was maybe required in previous MVC version?

Was it helpful?

Solution

This is a tricky area. There are many factors involved.

One of the reasons can be that the web browser is set for US english.

How about setting the culture information of the thread. You can do it either using Thread.CurrentThread.CurrentCulture or in the web config <globalization enableClientBasedCulture="true" culture="auto:en-NZ" uiCulture="auto:en"/> .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top