Custom Date Formats Model Binder in Umbraco
You built an Umbraco (or MVC)Ā site and it worked perfect on staging server but after pushed it to live server you got theĀ ModelState invalid issue when submitting data.
This is very common issue because not every servers are full support your date format (dd/MM/yyyy in my case). My solution is having a custom date model binder for DateTime and DateTime? type, below is my implementation
public class DateTimeModelBinder : DefaultModelBinder
{
Ā Ā private string _customFormat;
Ā Ā public DateTimeModelBinder(string customFormat)
Ā Ā {
Ā Ā Ā Ā _customFormat = customFormat;
Ā Ā }
Ā Ā public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
Ā Ā {
Ā Ā Ā Ā var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
Ā Ā Ā Ā return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture);
Ā Ā }
}
Now that we have the model binder, we need to associate it with all DateTime properties throughout our application. We do this by adding an instance of the binder to the ModelBinders.Binders collection from within Global.asax.cs.
protected void Application_Start()
{
Ā Ā //...
Ā Ā var binder = new DateTimeModelBinder(GetCustomDateFormat());
Ā Ā ModelBinders.Binders.Add(typeof(DateTime), binder);
Ā Ā ModelBinders.Binders.Add(typeof(DateTime?), binder);
}
using System.Web.Mvc;
using System.Globalization;
public class CustomEvents : ApplicationEventHandler
{ Ā Ā
Ā Ā protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
Ā Ā {
Ā Ā var binder = new DateTimeModelBinder(GetCustomDateFormat());
Ā Ā Ā Ā ModelBinders.Binders.Add(typeof(DateTime), binder);
Ā Ā Ā Ā ModelBinders.Binders.Add(typeof(DateTime?), binder);
Ā Ā }
}
This will associate our new binder with any properties or values of type DateTime or DateTime?. Now, whenever one of these types is encountered by MVC whilst trying to parse a POSTed value it will use our custom binder and therefore our custom format!