I\'m having a nightmare of a time with Dates. Were based in the UK, so our date format is dd/MM/yyyy. This is what users will type into the form when they want a certain dat
Got a solution, thanks to @Jon for the pointers:
public class GBDateModelBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string dateString = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
if (string.IsNullOrEmpty(dateString))
dateString = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
DateTime dt = new DateTime();
bool success = DateTime.TryParse(dateString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dt);
if (success)
{
return dt;
}
else
{
return null;
}
}
#endregion
}
then register in global.asax:
ModelBinders.Binders.Add(typeof(DateTime), new GBDateModelBinder());
UPDATE
altered this to allow for the same issue when POSTing!
In addition to Liam's answer:
For those who are still having this issue (!) and are trying to bind to a Nullable DateTime, make sure you register the correct type in global.asax:
ModelBinders.Binders.Add(typeof(DateTime), new GBDateModelBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new GBDateModelBinder());
Had me stumped for 15 minutes!