How can i tell my controller/model what kind of culture it should expect for parsing a datetime?
I was using some of this post to implement jquery d
I have a updated solution for MVC5 based on the Post of @gdoron. I will share it in case anyone else is looking for this. The class inherits from DefaultModelBinder
and has exception handling for invalid dates. It also can handle null values:
public class DateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object result = null;
var modelName = bindingContext.ModelName;
var attemptedValue = bindingContext.ValueProvider.GetValue(modelName)?.AttemptedValue;
// in datetime? binding attemptedValue can be Null
if (attemptedValue != null && !string.IsNullOrWhiteSpace(attemptedValue))
{
try
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
result = DateTime.Parse(value.AttemptedValue, CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
bindingContext.ModelState.AddModelError(modelName, e);
}
}
return result;
}
}
And just like the mentioned sample in the Global.Asax
write
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());