我有以下自定义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?
答案 0 :(得分:3)
您需要注册两次,如下所示:
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());