自定义ModelBinder不适用于Nullable类型

时间:2016-10-20 10:18:50

标签: c# asp.net-mvc model-binding

我有以下自定义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);
        }
    }

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

如何让ModelBinder适用于可为空的DateTime?

1 个答案:

答案 0 :(得分:3)

您需要注册两次,如下所示:

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