Reputation: 3924
I have an MVC View which has an optional <input />
for a Date.
The Model (Generated from a DB) has the DateTime
field as Not Null
If the user decides to leave the field blank, the View
will get passed back to the Controller
, which will then validate everything and save it away to a DB.
The issue comes in where the null value being passed back is either 1900-01-01 12:00:00 PM
OR DateTime.Min
, depending on the server (Right now two different Dev machines).
The Min Date
needed in the DB is 1900-01-01 12:00:00 PM
, so to circumvent this, I have the following check:
person.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;
Is this the best, or most correct way of checking for a supposedly null date being brought back from the Controller
?
Upvotes: 1
Views: 1218
Reputation: 14640
You could add a model binder.
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;
}
}
Register it in Global asax.
ModelBinders.Binders.Add(typeof(DateTime), new DateModelBinder());
Upvotes: 1