This is solved by implementing a DateTimeModelBinder
:
public class DateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object result = null;
string modelName = bindingContext.ModelName;
string attemptedValue = bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;
if (String.IsNullOrEmpty(attemptedValue))
{
return result;
}
try
{
result = DateTime.Parse(attemptedValue);
}
catch (FormatException e)
{
bindingContext.ModelState.AddModelError(modelName, e);
}
return result;
}
}
Register it for types DateTime
and DateTime?
on Global.asax.cs
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
...
}
Also configure globalization on your Web.config
:
<system.web>
...
<globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
...
</system.web>