如何在asp.net mvc中将datetime值作为URI参数传递?

时间:2020-11-25 03:26:51

I need to have an action parameter that has a datetime value? Is there a standard way to do this? I need to have something like:

我需要一个具有datetime值的操作参数?有标准的方法吗?我需要这样的东西:

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

but I'm only succeeding indoing it with something like:

但我只是成功地做了一些事情,比如:

mysite/Controller/Action/200909211020

and writing a custome function to deal with this format.

并编写一个custome函数来处理这种格式。

Again, looking for a standard or sanctioned ASP.net MVC way to do this.

同样,寻找一种标准或允许的ASP.net MVC方法来实现这一点。

8 个解决方案

#1


34  

The colon in your first example's url is going to cause an error (Bad Request) so you can't do exactly what you are looking for. Other than that, using a DateTime as an action parameter is most definitely possible.

第一个示例的url中的冒号将导致错误(错误请求),因此您不能准确地执行所查找的操作。除此之外,使用DateTime作为操作参数是非常可能的。

If you are using the default routing, this 3rd portion of your example url is going to pickup the DateTime value as the {id} parameter. So your Action method might look like this:

如果您使用的是缺省路由,那么示例url的第三部分将会将DateTime值作为{id}参数获取。你的行动方法可能是这样的:

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

You'll probably want to use a Nullable Datetime as I have, so if this parameter isn't included it won't cause an exception. Of course, if you don't want it to be named "id" then add another route entry replacing {id} with your name of choice.

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

As long as the text in the url will parse to a valid DateTime value, this is all you have to do. Something like the following works fine and will be picked up in your Action method without any errors:

只要url中的文本将解析为一个有效的DateTime值,这就是您所要做的。类似以下的工作很好,并且将在您的操作方法中得到,没有任何错误:

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

The catch, in this case of course, is that I did not include the time. I'm not sure there are any ways to format a (valid) date string with the time not represented with colons, so if you MUST include the time in the url, you may need to use your own format and parse the result back into a DateTime manually. Say we replace the colon with a "!" in the actionlink: new { id = DateTime.Now.ToString("dd-MM-yyyy HH!mm") }.

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

Your action method will fail to parse this as a date so the best bet in this case would probably to accept it as a string:

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

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

Edit: As noted in the comments, there are some other solutions arguably better than mine. When I originally wrote this answer I believe I was trying to preserve the essence of the date time format as best possible, but clearly URL encoding it would be a more proper way of handling this. +1 to Vlad's comment.

编辑:正如评论中所指出的,有一些其他的解决方案可以说比我的更好。当我最初写这个答案的时候,我相信我是在尽量保留日期时间格式的本质,但是很明显,URL编码是一种更合适的处理方式。+ 1弗拉德的评论。

#2


25  

Try to use toISOString(). It returns string in ISO8601 format.

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

from javascript

从javascript

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

from c#

从c #

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

#3


13  

Use the ticks value. It's quite simple to rebuild into a DateTime structure

使用蜱虫的价值。将其重新构建为DateTime结构非常简单

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

#4


5  

Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

net MVC的典型URI格式是Controller/Action/Id,其中Id为整数

I would suggest sending the date value as a parameter rather than as part of the route:

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

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

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

如果它仍然给您带来问题,那么日期可能包含URI中不允许且需要编码的字符。查看:

 encodeURIComponent(yourstring)

It is a method within Javascript.

它是Javascript中的一个方法。

On the Server Side:

在服务器端:

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

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.

简单地说,只要名称相同,任何url参数都可以映射到操作方法参数。

#5


4  

I thought I'd share what works for me in MVC5 for anyone that comes looking for a similar answer.

我想我可以在MVC5中分享我的工作,对于任何寻求类似答案的人来说。

My Controller Signature looks like this:

我的控制器签名如下:

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

}

My ActionLink looks like this in Razor:

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

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

This gives a URL like this:

它给出这样的URL:

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

Which encodes the date and time as it should.

它应该对日期和时间进行编码。

#6


1  

Since MVC 5 you can use the built in Attribute Routing package which supports a datetime type, which will accept anything that can be parsed to a DateTime.

由于MVC 5,您可以使用内置的属性路由包,它支持datetime类型,可以接受任何可以解析到datetime的内容。

e.g.

如。

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

More info here.

更多的信息在这里。

#7


0  

You should first add a new route in global.asax:

你应该先在全球增加一条新的航线。


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

The on your Controller:

在你的控制器:



        public ActionResult MyActionName(DateTime date)
        {

        }

Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.

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

#8


0  

Split out the Year, Month, Day Hours and Mins

把年份、月份、白天的时间和分钟分开

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

Use a cascading If Statement to Build up the datetime from the parameters passed into the Action

使用级联If语句从传递到操作的参数构建datetime

    ' 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

(Apologies for the vb.net but you get the idea :P)

(为vb.net向大家道歉,但是大家知道P)

#1


34  

The colon in your first example's url is going to cause an error (Bad Request) so you can't do exactly what you are looking for. Other than that, using a DateTime as an action parameter is most definitely possible.

第一个示例的url中的冒号将导致错误(错误请求),因此您不能准确地执行所查找的操作。除此之外,使用DateTime作为操作参数是非常可能的。

If you are using the default routing, this 3rd portion of your example url is going to pickup the DateTime value as the {id} parameter. So your Action method might look like this:

如果您使用的是缺省路由,那么示例url的第三部分将会将DateTime值作为{id}参数获取。你的行动方法可能是这样的:

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

You'll probably want to use a Nullable Datetime as I have, so if this parameter isn't included it won't cause an exception. Of course, if you don't want it to be named "id" then add another route entry replacing {id} with your name of choice.

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

As long as the text in the url will parse to a valid DateTime value, this is all you have to do. Something like the following works fine and will be picked up in your Action method without any errors:

只要url中的文本将解析为一个有效的DateTime值,这就是您所要做的。类似以下的工作很好,并且将在您的操作方法中得到,没有任何错误:

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

The catch, in this case of course, is that I did not include the time. I'm not sure there are any ways to format a (valid) date string with the time not represented with colons, so if you MUST include the time in the url, you may need to use your own format and parse the result back into a DateTime manually. Say we replace the colon with a "!" in the actionlink: new { id = DateTime.Now.ToString("dd-MM-yyyy HH!mm") }.

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

Your action method will fail to parse this as a date so the best bet in this case would probably to accept it as a string:

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

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

Edit: As noted in the comments, there are some other solutions arguably better than mine. When I originally wrote this answer I believe I was trying to preserve the essence of the date time format as best possible, but clearly URL encoding it would be a more proper way of handling this. +1 to Vlad's comment.

编辑:正如评论中所指出的,有一些其他的解决方案可以说比我的更好。当我最初写这个答案的时候,我相信我是在尽量保留日期时间格式的本质,但是很明显,URL编码是一种更合适的处理方式。+ 1弗拉德的评论。

#2


25  

Try to use toISOString(). It returns string in ISO8601 format.

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

from javascript

从javascript

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

from c#

从c #

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

#3


13  

Use the ticks value. It's quite simple to rebuild into a DateTime structure

使用蜱虫的价值。将其重新构建为DateTime结构非常简单

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

#4


5  

Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

net MVC的典型URI格式是Controller/Action/Id,其中Id为整数

I would suggest sending the date value as a parameter rather than as part of the route:

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

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

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

如果它仍然给您带来问题,那么日期可能包含URI中不允许且需要编码的字符。查看:

 encodeURIComponent(yourstring)

It is a method within Javascript.

它是Javascript中的一个方法。

On the Server Side:

在服务器端:

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

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.

简单地说,只要名称相同,任何url参数都可以映射到操作方法参数。

#5


4  

I thought I'd share what works for me in MVC5 for anyone that comes looking for a similar answer.

我想我可以在MVC5中分享我的工作,对于任何寻求类似答案的人来说。

My Controller Signature looks like this:

我的控制器签名如下:

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

}

My ActionLink looks like this in Razor:

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

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

This gives a URL like this:

它给出这样的URL:

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

Which encodes the date and time as it should.

它应该对日期和时间进行编码。

#6


1  

Since MVC 5 you can use the built in Attribute Routing package which supports a datetime type, which will accept anything that can be parsed to a DateTime.

由于MVC 5,您可以使用内置的属性路由包,它支持datetime类型,可以接受任何可以解析到datetime的内容。

e.g.

如。

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

More info here.

更多的信息在这里。

#7


0  

You should first add a new route in global.asax:

你应该先在全球增加一条新的航线。


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

The on your Controller:

在你的控制器:



        public ActionResult MyActionName(DateTime date)
        {

        }

Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.

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

#8


0  

Split out the Year, Month, Day Hours and Mins

把年份、月份、白天的时间和分钟分开

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

Use a cascading If Statement to Build up the datetime from the parameters passed into the Action

使用级联If语句从传递到操作的参数构建datetime

    ' 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

(Apologies for the vb.net but you get the idea :P)

(为vb.net向大家道歉,但是大家知道P)