自定义 ModelBinder 不适用于可空类型

Custom ModelBinder not working for Nullable types

我有以下用于 DateTime 的自定义 ModelBinder:

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);
        }
    }

如果我在 Action 中将参数指定为可为 null 的 DateTime (DateTime? dob),则 ModelBinder 不会触发。

如何让 ModelBinder 为可为 null 的 DateTime 工作?

需要注册两次,如下:

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