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

发布于 2024-07-29 10:54:00 字数 284 浏览 6 评论 0原文

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

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

但我只是成功地做到了类似的东西:

mysite/Controller/Action/200909211020

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

再次,寻找标准或认可的 ASP.net MVC 方法来执行此操作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

欢烬 2024-08-05 10:54:01

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

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

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

 Int64 nTicks = DateTime.Now.Ticks;
 ....
 DateTime dtTime = new DateTime(nTicks);
走过海棠暮 2024-08-05 10:54:01

我想我应该向任何寻求类似答案的人分享 MVC5 中对我有用的内容。

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

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

}

我的 ActionLink 在 Razor 中如下所示:

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

这给出了如下 URL:

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

它按应有的方式对日期和时间进行编码。

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

My Controller Signature looks like this:

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

}

My ActionLink looks like this in Razor:

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

This gives a URL like this:

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

Which encodes the date and time as it should.

不醒的梦 2024-08-05 10:54:01

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 参数都可以映射到操作方法参数。

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

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:

 encodeURIComponent(yourstring)

It is a method within 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.

隔纱相望 2024-08-05 10:54:01

拆分年、月、日、小时和分钟

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

使用级联 If 语句从传递到操作的参数中构建日期时间

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

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

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

椒妓 2024-08-05 10:54:01

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

例如

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

更多信息

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.

e.g.

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

More info here.

孤凫 2024-08-05 10:54:01

我意识到在后面添加斜线后它就可以工作了

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

i realize it works after adding a slash behind like so

mysite/Controller/Action/21-9-2009 10:20/
草莓酥 2024-08-05 10:54:01

您应该首先在 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。 如果不是,那么您可以有另一个日期时间表示形式。

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.

抱着落日 2024-08-05 10:54:01

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

有关使用 DateTime Parse 方法的更多信息,请参阅此链接:日期时间解析方法

string StringDateToDateTime(string date)
    {
        DateTime dateFormat = DateTime.Parse(date);
        return dateFormat ;
    }

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

I have the same problem. I use DateTime.Parse Method. and in the URL use this format to pass my DateTime parameter 2018-08-18T07:22:16

for more information about using DateTime Parse method refer to this link : DateTime Parse Method

string StringDateToDateTime(string date)
    {
        DateTime dateFormat = DateTime.Parse(date);
        return dateFormat ;
    }

I hope this link helps you.

ぃ双果 2024-08-05 10:54:00

第一个示例的网址中的冒号将导致错误(错误请求),因此您无法准确执行您要查找的操作。 除此之外,使用 DateTime 作为操作参数绝对是可能的。

如果您使用默认路由,示例 URL 的第三部分将获取 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") }) %>

当然,在这种情况下,问题是我没有包括时间。 我不确定是否有任何方法可以格式化(有效)日期字符串,其中时间不以冒号表示,因此如果您必须在网址中包含时间,您可能需要使用自己的格式并将结果解析回手动输入日期时间。 假设我们将冒号替换为“!” 在操作链接中: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。

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.

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:

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.

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:

<%=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") }.

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.

尝试使用 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);
}

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

from javascript

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

from c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文