自定义ModelBinder不适用于可空类型
本文关键字:类型 适用于 ModelBinder 不适用 自定义 | 更新日期: 2023-09-27 18:14:03
我为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中的参数指定为可空的DateTime (DateTime? dob
),则ModelBinder不会触发。
我如何使ModelBinder为可空的DateTime工作?
需要注册两次,如下所示:
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());