如何在asp.net mvc中将日期时间值作为URI参数传递?

时间:2009-08-03 19:34:12

标签: asp.net-mvc datetime uri

我需要一个具有日期时间值的动作参数?有没有标准的方法来做到这一点?我需要有类似的东西:

mysite/Controller/Action/21-9-2009 10:20

但是我只是用以下的东西来成功:

mysite/Controller/Action/200909211020

并编写一个自定义函数来处理这种格式。

再次,寻找标准或认可的ASP.net MVC方式来做到这一点。

10 个答案:

答案 0 :(得分:36)

第一个示例网址中的冒号会导致错误(错误请求),因此您无法完全按照自己的意愿行事。除此之外,绝对可以使用DateTime作为动作参数。

如果您使用默认路由,示例网址的第3部分将将DateTime值作为{id}参数获取。所以你的Action方法可能如下所示:

public ActionResult Index(DateTime? id)
{
    return View();
}

您可能希望使用Nullable Datetime,因此如果不包含此参数,则不会导致异常。当然,如果您不希望将其命名为“id”,则添加另一个路径条目,将{id}替换为您选择的名称。

只要url中的文本将解析为有效的DateTime值,这就是您所要做的。像下面这样的工作正常,将在你的Action方法中选择,没有任何错误:

<%=Html.ActionLink("link", "Index", new { id = DateTime.Now.ToString("dd-MM-yyyy") }) %>

在这种情况下,捕获的是我没有包括时间。我不确定是否有任何方法可以使用冒号表示的时间格式化(有效)日期字符串,因此如果您必须在URL中包含时间,则可能需要使用自己的格式并将结果解析回一个DateTime手动。假设我们用“!”替换冒号。在actionlink中:new { id = DateTime.Now.ToString("dd-MM-yyyy HH!mm") }

您的操作方法无法将其解析为日期,因此在这种情况下最好的选择可能是将其作为字符串接受:

public ActionResult Index(string id)
{
    DateTime myDate;
    if (!string.IsNullOrEmpty(id))
    {
        myDate = DateTime.Parse(id.Replace("!", ":"));
    }
    return View();
}

编辑:正如评论中所述,还有其他一些解决方案可以说比我的更好。当我最初写这个答案时,我相信我试图尽可能地保留日期时间格式的本质,但显然URL编码它将是一种更合适的处理方式。弗拉德的评论+1。

答案 1 :(得分:28)

尝试使用toISOString()。它以ISO8601格式返回字符串。

来自javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

来自c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

答案 2 :(得分:13)

使用刻度值。重建为DateTime结构非常简单

 Int64 nTicks = DateTime.Now.Ticks;
 ....
 DateTime dtTime = new DateTime(nTicks);

答案 3 :(得分:5)

ASP .NET MVC的URI的典型格式是Controller / Action / Id,其中Id是整数

我建议将日期值作为参数而不是作为路线的一部分发送:

 mysite/Controller/Action?date=21-9-2009 10:20

如果仍然存在问题,则日期可能包含URI中不允许的字符,需要进行编码。退房:

 encodeURIComponent(yourstring)

这是Javascript中的一种方法。

在服务器端:

public ActionResult ActionName(string date)
{
     DateTime mydate;
     DateTime.Tryparse(date, out mydate);
}

仅供参考,只要名称相同,任何url参数都可以映射到操作方法参数。

答案 4 :(得分:5)

我想我会在MVC5中与那些寻找类似答案的人分享对我有用的东西。

我的控制器签名如下所示:

public ActionResult Index(DateTime? EventDate, DateTime? EventTime)
{

}

我的ActionLink在Razor中看起来像这样:

@Url.Action("Index", "Book", new { EventDate = apptTime, EventTime = apptTime})

这会提供如下网址:

Book?EventDate=01%2F20%2F2016%2014%3A15%3A00&EventTime=01%2F20%2F2016%2014%3A15%3A00

编码日期和时间。

答案 5 :(得分:1)

从MVC 5开始,您可以使用支持datetime类型的内置Attribute Routing包,它将接受任何可以解析为DateTime的内容。

e.g。

[GET("Orders/{orderDate:datetime}")]

更多信息here

答案 6 :(得分:0)

您应首先在global.asax中添加新路由:


routes.MapRoute(
                "MyNewRoute",
                "{controller}/{action}/{date}",
                new { controller="YourControllerName", action="YourActionName", date = "" }
            );

你的控制器:



        public ActionResult MyActionName(DateTime date)
        {

        }

请记住将默认路由保留在RegisterRoutes方法的底部。请注意,引擎将尝试将您在{date}中发送的任何值转换为DateTime示例,因此如果无法转换它,则会抛出异常。如果您的日期字符串包含空格或:您可以HTML.Encode它们,以便可以正确解析URL。如果不是,那么您可以使用另一个DateTime表示。

答案 7 :(得分:0)

分出年,月,日时和分钟

routes.MapRoute(
            "MyNewRoute",
            "{controller}/{action}/{Year}/{Month}/{Days}/{Hours}/{Mins}",
            new { controller="YourControllerName", action="YourActionName"}
        );

使用级联If语句从传递给Action

的参数构建日期时间
    ' Build up the date from the passed url or use the current date
    Dim tCurrentDate As DateTime = Nothing
    If Year.HasValue Then
        If Month.HasValue Then
            If Day.HasValue Then
                tCurrentDate = New Date(Year, Month, Day)
            Else
                tCurrentDate = New Date(Year, Month, 1)
            End If
        Else
            tCurrentDate = New Date(Year, 1, 1)
        End If
    Else
        tCurrentDate = StartOfThisWeek(Date.Now)
    End If

(为vb.net道歉,但你明白了:P)

答案 8 :(得分:0)

我意识到像这样在后面加上斜杠

mysite/Controller/Action/21-9-2009 10:20/

答案 9 :(得分:0)

我有同样的问题。我使用DateTime.Parse方法。并在URL中使用此格式传递我的DateTime参数 2018-08-18T07:22:16

有关使用DateTime Parse方法的更多信息,请参见以下链接:DateTime Parse Method

Method Requested_Resource(and GET parameters if any) HTTP_Version \r\n
Headers ('\r\n' after each header)
\r\n
Body

希望此链接对您有所帮助。

相关问题