I have the following custom 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);
}
}
If I specify the argument in my Action as a nullable DateTime ( DateTime? dob
), the ModelBinder does not fire.
How can I make the ModelBinder work for nullable DateTime?
You need to register it twice, like this:
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.