Reputation: 7823
I have the following custom ModelBinder for DateTime:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult value = null;
try
{
value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture);
}
catch (Exception)
{
// If there is a place where DateTime got used which "Bypassed" our EditorTemplate, it means the format will be the default format.
// So let's allow the Model Binder to at least try to Parse the date with the default format.
return DateTime.Parse(value.AttemptedValue);
}
}
If I specify the argument in my Action as a nullable DateTime (DateTime? dob
), the ModelBinder does not fire.
How can I make the ModelBinder work for nullable DateTime?
Upvotes: 2
Views: 546
Reputation: 24279
You need to register it twice, like this:
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());
Upvotes: 4