Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Passing JSON DateTime to controller not mapping to controller parameters

I am using a jQuery calendar to display events, which is designed to pull data from the server. On innit the calendar fires off a AJAX request to get an array of events objects (json encoded). All good so far. However, this request includes a JSON encoded date and time (at leats my implimentation does). The code looks like this:

data: function (start, end, callback) {
        $.post('/planner/GetPlannerEvents', { test: "test", start: JSON.stringify(start), end: JSON.stringify(end) }, function (result) { callback(result); });
    }

The declaration for the GetPlannerEvents controller method looks like this:

public ActionResult GetPlannerEvents(DateTime start, DateTime end)

The problem is that asp.net mvc 2 cannot seem to automatically parse the json encoded datetime and as such complains that the start and end values are null.

Is there another method I should be using to pass the javascript dates to the server so that they may be parsed correctly?

Thanks,

like image 492
Sergio Avatar asked Oct 14 '10 12:10

Sergio


2 Answers

You shouldn't be JSON encoding the dates with stringify because the default model binder doesn't expect JSON. Try this:

$.post('/planner/GetPlannerEvents', { start: start.toUTCString(), 
    end: end.toUTCString() }, function (result) {
    callback(result); 
});
like image 136
Darin Dimitrov Avatar answered Nov 18 '22 16:11

Darin Dimitrov


Try to use date.toISOString() to pass data to server. It returns string in ISO8601 format. Also this method can be used to format dates for using in uri.

$.post('/planner/GetPlannerEvents', { start: start.toISOString(), 
    end: end.toISOString() }, function (result) {
    callback(result); 
});

Why toISOString is better than toUTCString?
toUTCString converts to human readable string in the UTC time zone.
toISOString converts to universal ISO format which allows to resolve issue with regional settings and different formats.

like image 28
rnofenko Avatar answered Nov 18 '22 15:11

rnofenko