asp.net-mvc 如何在 asp.net mvc 中将日期时间值作为 URI 参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1224201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I pass a datetime value as a URI parameter in asp.net mvc?
提问by GilShalit
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:
我需要一个具有日期时间值的操作参数吗?有没有标准的方法来做到这一点?我需要有类似的东西:
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.
并编写一个客户函数来处理这种格式。
Again, looking for a standard or sanctioned ASP.net MVC way to do this.
再次,寻找标准或认可的 ASP.net MVC 方式来做到这一点。
采纳答案by Kurt Schindler
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} 参数。因此,您的 Action 方法可能如下所示:
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 值,这就是您所要做的。像下面这样的东西工作正常,并且会在你的 Action 方法中被拾取而没有任何错误:
<%=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 中包含时间,你可能需要使用你自己的格式并将结果解析回手动日期时间。假设我们用“!”替换冒号 在操作链接中: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 对弗拉德的评论。
回答by rnofenko
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);
}
回答by Gordon Thompson
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);
回答by Sam Ellis
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.
哪个编码日期和时间,因为它应该。
回答by Roland Schaer
Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer
ASP .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 参数都可以映射到操作方法参数。
回答by Angie Loo
i realize it works after adding a slash behind like so
我意识到在像这样添加斜杠后它可以工作
mysite/Controller/Action/21-9-2009 10:20/
回答by JonAlb
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 语句根据传递给 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
(Apologies for the vb.net but you get the idea :P)
(为 vb.net 道歉,但你明白了:P)
回答by demoncodemonkey
Since MVC 5 you can use the built in Attribute Routingpackage which supports a datetimetype, which will accept anything that can be parsed to a DateTime.
从 MVC 5 开始,您可以使用支持类型的内置属性路由包datetime,该包将接受可以解析为 DateTime 的任何内容。
e.g.
例如
[GET("Orders/{orderDate:datetime}")]
More info here.
更多信息在这里。
回答by Freddy
You should first add a new route in global.asax:
您应该首先在 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.
请记住将默认路由保留在 RegisterRoutes 方法的底部。请注意,引擎将尝试将您在 {date} 中发送的任何值转换为 DateTime 示例,因此如果无法转换,则会引发异常。如果您的日期字符串包含空格或 : 您可以对它们进行 HTML.Encode,以便正确解析 URL。如果不是,那么您可以有另一个 DateTime 表示。

