MVC处理从视图到控制器的空日期

时间:2014-07-23 07:56:18

标签: sql asp.net-mvc date datetime

我有一个MVC视图,其日期有可选 <input />
模型(从数据库生成)的DateTime字段为Not Null

如果用户决定将该字段留空,View将被传递回Controller,然后1900-01-01 12:00:00 PM将验证所有内容并将其保存到数据库中。

问题在于传递的 null 值是DateTime.Min OR Min Date,具体取决于服务器(现在是两台不同的Dev机器)。

数据库中所需的1900-01-01 12:00:00 PMperson.PaidDate = person.PaidDate == DateTime.MinValue || person.PaidDate == DateTime.Parse("1900-01-01 12:00:00 PM") ? DateTime.Parse("1900/01/01 12:00:00") : person.PaidDate; ,所以为了避免这种情况,我有以下检查:

Controller

这是检查从{{1}}带回的假定为空的日期的最佳或最正确方法吗?

1 个答案:

答案 0 :(得分:1)

您可以添加模型装订器。

public class DateModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var dateTime = bindingContext.Model as DateTime?;
        var result = dateTime.GetValueOrDefault() == DateTime.MinValue 
            ? DateTime.Parse(SqlDateTime.MinValue.ToString()) 
            : dateTime.Value;
        return result;
    }
}

在Global asax中注册。

ModelBinders.Binders.Add(typeof(DateTime), new DateModelBinder());