开发者

How do I pass a date via the URL, for my Action to read in MVC?

开发者 https://www.devze.com 2022-12-13 21:11 出处:网络
How do I pass a date via the URL? Here is what I am trying to do, as as you\'ll see th开发者_StackOverflow社区e date uses forward slashes which are invalid in the URL

How do I pass a date via the URL?

Here is what I am trying to do, as as you'll see th开发者_StackOverflow社区e date uses forward slashes which are invalid in the URL

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


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消