1

the DateTime that comes from POST is binded correctly (according to my computer's format)

but DateTime values that come from GET doesn't bind correctly, it is using a different format

my format is dd.MM.yyyy, in GET it uses MM.dd.yyyy instead

I don't have this problem if I use the en-US format  (which is MM/dd/yyyy)

anybody knows how to fix this?

is this a mvc bug ? (it doesn't consider Culture when binding get requests)

Omu
  • 69,856
  • 92
  • 277
  • 407

1 Answers1

8

No, it seems it isn't a bug. You can get more details here: MVC DateTime binding with incorrect date format

I've been using the following ModelBinder to solve that problem.

public class CurrentCultureDateTimeBinder : IModelBinder
{
    private const string PARSE_ERROR = "\"{0}\" is not a valid date";
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueProviderResult == null) return null;

        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
        {
            return DateTime.Parse(date);
        }
        catch (Exception)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(PARSE_ERROR, bindingContext.ModelName));
            return null;
        }
    }
}

Hope it helps.

Community
  • 1
  • 1
CGK
  • 2,662
  • 21
  • 24
  • 2
    @Omu It works because DateTime.Parse(String) uses the current thread culture (making the binder Culture aware). In contrast, the default binder uses CultureInfo.InvariantCulture. You can see more details here: http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx – CGK Dec 01 '10 at 14:50