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 the guys DateTime
and DateTime?
in the 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 in your Web.config
:
<system.web>
...
<globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
...
</system.web>
The best way, for me, is the format in which I don’t need to convert any time. Try to work in a pattern in which you will have the least effort possible.
– Jhonathan
but I cannot pass through querystring the Brazil dd/mm/yyyy pattern and I have problems displaying values in this format, so I changed to yyyy-MM-dd
– Dorathoto
It would not be better if you set the culture on the web.config and so already deal with dates in Brazilian format?
– Jhonathan
I already did and still in the querystring he changes
– Dorathoto