monstertjie_za monstertjie_za - 1 year ago 137
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;
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 Source

You need to register it twice, like this:

ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download