我创建了一个自定义模型绑定器来处理日期。我在使用可空的DateTimes时遇到了麻烦。
目前,如果ViewModel属性的DataType设置为DataType.Data,则会正确调用自定义模型绑定器并生成三个文本框来表示日,月和年。如果我删除了该DataType,则不会调用ModelBinder。
如果所有这些盒子都有价值,那么一切正常。当您将字段留空时会出现问题,因为某些日期是可选的,这将是有效的。在这个例子中,我们尝试将null设置为DataType值为Date的属性,这会引发错误: -
值不能为空。 参数名称:值
如何在不使用Date的DataAnnotation的情况下正确设置自定义模型绑定器以绑定到DateTime?
这是我的CustomModelBinder的装饰器
[ModelBinderType(typeof (DateTime), typeof (DateTime?))]
public class DateTimeModelBinder : IModelBinder
{
这是我的ViewModel
public class TestModel
{
[DisplayName("")]
[DataType(DataType.Date)]
public DateTime? TestTime { get; set; }
}
这是我使用Autofac绑定自定义模型绑定器的DI
private static void SetupModelBinders(ContainerBuilder builder)
{
builder.RegisterModule<ModelBinderModule>();
builder.RegisterModelBinders(typeof(DateTimeModelBinder).Assembly);
builder.RegisterModelBinderProvider();
}
很明显,Custom Model Binder没有正确绑定到DateTime?因为它取决于存在的DataType。但是什么是将ModelBinder与DateTime和可空的DatTime链接的替代方法。理想情况下,在整个系统中,如果需要,可以逐个进行。
感谢。