How do I pass a date via the URL, for my Action to

2019-04-20 18:06发布

How do I pass a date via the URL?

Here is what I am trying to do, as as you'll see the date uses forward slashes which are invalid in the URL

http://localhost/Controller/Action/id=0d5375aa-6d43-42f1-91f0-ea73d9beb361&date=02/12/2009

4条回答
你好瞎i
2楼-- · 2019-04-20 18:23

The ISO 8601 standard is yyyy-MM-dd, which is unambiguous and does not contain any invalid URL characters, and works fine in DateTime.Parse/TryParse.

Another option is to use whatever format you want and simply encode the URL using HttpServerUtility.UrlEncode/UrlDecode.

查看更多
放我归山
3楼-- · 2019-04-20 18:28

You could URL encode it, but passing a DateTime around as a string is always a bit tricky because you may run into parsing errors if the request ever crosses culture boundaries.

A better option is to convert the DateTime to Ticks and pass that number around.

查看更多
做个烂人
4楼-- · 2019-04-20 18:31

You could pass a date in the query string using a specific format, say yyyymmdd and then parse it correctly in your Controller.

&date=02/12/2009
change to
&date=20091202   (yyyymmdd)

You could either create a wrapper around the DateTime object that was instantiated using this new format or just parse it yourself in the Controller.

public MyWrapperDate(int date)
{
    int year = date / 10000;
    int month = ((date - (10000 * year)) / 100);
    int day = (date - (10000 * year) - (100 * month));

    this.DateTimeObject = new DateTime(year, month, day);
}
查看更多
Evening l夕情丶
5楼-- · 2019-04-20 18:38

MVC uses the current culture when generating URL and binding Models. It makes sense in some scenarios (like when you have a textbox and the user enters the date there) but there are often problems. If you have different cultures then it is easier if values are always in the format for invariant culture.

In your case I would pass the value as a string rendered by invariant culture. Then I would use a CustomModelBinder to fill the property in the Model.

查看更多
登录 后发表回答