Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MVC and DateTime in action controller model

I have this controller action :

[HttpGet]
public ActionResult CreateForm(Models.ReminderModel model)
{
    if (model.FkUserId == null && model.FkRoleId == null) {
        model.FkUserId = UserSession.Current.UserId;
        model.ReminderDate = DateTime.UtcNow;
    }

    return View(model);
}

The action behaves normally if no URL param is specified, but when I specify some data, everything gets set BUT ReminderDate. For example, the request is performed with

model[0][name]:FkUserId
model[0][value]:2
....
model[2][name]:ReminderDate
model[2][value]:2013-03-09T10:33:04.934Z
...

Note : the params are serialized view jQuery and always worked fine until now. It's the first time we try to pass a DateTime back to a controller action.

In the action controller, model.FKUserId will correctly be set, however ReminderDate will be set to "0001-01-01T00:00:00.000Z".

What am I missing?

** Update **

As it turned out, C# will not work with ISO formatted date time strings. It prefers UTC ones. Something like 2013-03-05T16:23:00.000Z needs to be sent as u20130305212358000 (EST). A binding would've been sufficient as well, but I think this is the best solution.

like image 405
Yanick Rochon Avatar asked Mar 05 '13 15:03

Yanick Rochon


1 Answers

You would get that date of 1/1/0001 because when MVC can't find a value to supply, or can't apply the available value for some reason, the date's default remains, which for DateTime is 1/1/0001 or DateTime.MinValue. If you used DateTime?, you would see null.

It would be good to use Fiddler or Firebug to inspect the request and see what the value being sent is. It most likely may need to be adjusted. You could also check the current form's response via the Form collection and manually convert the value yourself too.

Some alternatives is MVC model binding (though some mention cons to this approach). Some more info is listed below:

  • http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx
  • Custom DateTime model binder in Asp.net MVC
like image 109
Brian Mains Avatar answered Oct 28 '22 12:10

Brian Mains