[英]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在可为空的DateTime上工作?
您需要注册两次,如下所示:
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.