monstertjie_za monstertjie_za - 1 month ago 11
C# Question

Custom ModelBinder not working for Nullable types

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?

Answer

You need to register it twice, like this:

ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());