Farhad-Taran
Farhad-Taran

Reputation: 6512

asp.net mvc controller does not recognize DateTime url parameter?

I am encoding an Iframe url with some date parameters:

var object = {
                profileID: self.profileID(),
                organisationID: self.organisationID(),
                startDate: self.startDate(), // 09/04/2013 
                endDate: self.endDate() // 17/04/2013 
            };
iFrame.src = "ExportReportAllMediaDetailsCsv/?" + $.param(object);

the encoded url:

http://dev.neptune.local/Report/ExportReportAllMediaDetailsCsv/?profileID=41&organisationID=2252&startDate=09%2F04%2F2013&endDate=17%2F04%2F2013

however the method that is being called sometimes does not recognize the datetimes being passed in:

The parameters dictionary contains a null entry for parameter 'endDate' of non-nullable type 'System.DateTime'

this is the method signature:

[CustomAuthorize(Definitions.RoleAnalystManager, Definitions.RoleProjectManager)]
public ActionResult ExportReportAllMediaDetailsCsv(int profileID, int organisationID, DateTime startDate, DateTime endDate)

Upvotes: 4

Views: 4203

Answers (3)

Farhad-Taran
Farhad-Taran

Reputation: 6512

To resolve this issue I Converted the dates to UTC date time strings:

var object = {
                profileID: self.profileID(),
                organisationID: self.organisationID(),
                startDate: getUtcDateString(self.startDate()),
                endDate:getUtcDateString(self.endDate())
            };

function getUtcDateString(gbDate) {
    var dayMonthYear = gbDate.split("/"),
        newDate = new Date(dayMonthYear[2], dayMonthYear[1]-1, dayMonthYear[0]);
    return newDate.toUTCString();
}

Upvotes: 1

Ant P
Ant P

Reputation: 25231

You're using UK-formatted date strings. Since only endDate isn't working, my guess is that startDate is being recognised as the 4th of September. On the other hand, because there is no 17th month of the year, endDate can't be bound to a DateTime object.

It sounds like you need to set your culture correctly. Try adding the following to your Web.Config, under <system.web>:

<globalization requestEncoding="utf-8" responseEncoding="utf-8"
    culture="en-GB" />

For more info on globalization, see http://msdn.microsoft.com/en-us/library/c6zyy3s9(v=vs.100).aspx

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27614

It look like endDate sometimes is null (or simply it's not set), so you have to declare parameter as nullable type (DateTime?):

public ActionResult ExportReportAllMediaDetailsCsv
    (int profileID, int organisationID, DateTime startDate, DateTime? endDate)

On the other hand it may be because datetime format is not recognized, so basically it can't be parsed as a valid DateTime value.

Upvotes: 0

Related Questions