【问题标题】:asp.net mvc controller does not recognize DateTime url parameter?asp.net mvc 控制器无法识别 DateTime url 参数?
【发布时间】:2013-04-22 19:35:55
【问题描述】:

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

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)

【问题讨论】:

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


    【解决方案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】:

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

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

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

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

      【讨论】:

        【解决方案3】:

        看起来endDate 有时为空(或者只是未设置),因此您必须将参数声明为可空类型(DateTime?):

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

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

        【讨论】:

        • 但即使传入且不为空也会抛出异常,除非两个日期都已设置,否则无法发布请求
        • 可能是日期时间格式错误,您是否尝试过以不同格式发送日期时间字符串?
        • 那么日期时间格式通常取决于文化。检查standard DateTime format strings
        • 还检查@AntP 答案,这可能更适合设置应用程序范围的文化而不是格式化您的日期时间字符串。这取决于你需要什么。
        猜你喜欢
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 2018-11-11
        • 2011-03-09
        • 2019-09-18
        • 1970-01-01
        • 1970-01-01
        • 2016-05-30
        相关资源
        最近更新 更多