views:

804

answers:

4

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.

thanks

Gil

A: 

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.

Freddy
A: 

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

 Int64 nTicks = DateTime.Now.Ticks;
 ....
 DateTime dtTime = new DateTime(nTicks);
Gordon Carpenter-Thompson
This is neat. What I like about my solution is that the URI is still readable.
GilShalit
+1  A: 

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,mydate);
}

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

JookyDFW
+2  A: 

The semi-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 semi-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 semicolon 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();
}

Disclaimer: All my examples are with the default routing to prevent (or cause?) confusion. I highly recommend calling this parameter something other than id. Also, I tried to come up with a solution closest to what you seem to be looking for, and frankly, one that I don't particularly like. I highly suggest considering why such a read-able date (time in particular) is necessary. Doing something like your second example by just displaying the ticks may be a better solution than the one I just proposed.

Kurt Schindler
Thanks for the comprehensive overview. I do need to receive the time as part of the parameter, because this is a sort of routing application where the trips have a desired time. So I think I will stick with my custom format method.
GilShalit