I have created a custom model binder to work with dates. I am having trouble working with nullable DateTimes.
At present if the DataType of a ViewModel property is set to DataType.Data then the custom model binder is correctly called and produces three text boxes to represent day, month and year. If I remove that DataType then the ModelBinder is not called.
If all those boxes have a value then everything works fine. The issue comes when you leave the fields blank, as some dates are optional this would be valid. In this instance we try to set null to a property that has a DataType value of Date, which throws an error:-
Value cannot be null. Parameter name: value
How do I correctly setup the custom model binder to bind to a DateTime without using the DataAnnotation of Date?
This is the decorator of my CustomModelBinder
[ModelBinderType(typeof (DateTime), typeof (DateTime?))]
public class DateTimeModelBinder : IModelBinder
{
This is my ViewModel
public class TestModel
{
[DisplayName("")]
[DataType(DataType.Date)]
public DateTime? TestTime { get; set; }
}
And this is my DI to bind the custom model binder using Autofac
private static void SetupModelBinders(ContainerBuilder builder)
{
builder.RegisterModule<ModelBinderModule>();
builder.RegisterModelBinders(typeof(DateTimeModelBinder).Assembly);
builder.RegisterModelBinderProvider();
}
It is clear that the Custom Model Binder is not correctly binding to DateTime? as it is dependent upon the DataType being present. But what is an alternative way of linking that ModelBinder with DateTime and nullable DatTime. Ideally throughout the system, but can do it on a one by one basis if needed.
Thanks.