How do I pass a datetime value as a URI parameter in asp.net mvc?

前端 未结 10 1001
孤城傲影
孤城傲影 2020-12-04 18:58

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/2         


        
相关标签:
10条回答
  • 2020-12-04 19:43

    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.

    0 讨论(0)
  • 2020-12-04 19:44

    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.

    0 讨论(0)
  • 2020-12-04 19:44

    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)

    0 讨论(0)
  • 2020-12-04 19:44

    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.

    0 讨论(0)
提交回复
热议问题