asp.net mvc控制器无法识别DateTime url参数?

时间:2013-04-29 07:41:08

标签: c# javascript asp.net-mvc knockout.js

我正在使用一些日期参数对Iframe网址进行编码:

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);

已编码的网址:

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

然而,被调用的方法有时无法识别传入的日期时间:

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

这是方法签名:

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

3 个答案:

答案 0 :(得分:1)

您使用的是英国格式的日期字符串。由于只有endDate无效,我的猜测是startDate被认定为9月4日。另一方面,由于一年中没有第17个月,endDate无法绑定到DateTime个对象。

听起来你需要正确设置你的文化。尝试将以下内容添加到您的Web.Config,<system.web>下:

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

有关全球化的更多信息,请参阅http://msdn.microsoft.com/en-us/library/c6zyy3s9(v=vs.100).aspx

答案 1 :(得分:1)

要解决此问题,我将日期转换为UTC日期时间字符串:

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();
}

答案 2 :(得分:0)

看起来endDate有时候是空的(或者只是没有设置),所以你必须将参数声明为可空类型(DateTime?):

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

另一方面,可能是因为日期时间格式无法识别,所以基本上它不能被解析为有效的DateTime值。

相关问题