Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I format MVC Route parameters?
    primarykey
    data
    text
    <p>I have the following route mapped in my test MVC3 project -</p> <pre><code>routes.MapRoute( "TestRoute", "test/{DateFrom}/{DateTo}", new { controller = "Home", action = "TestRoute" } ); </code></pre> <p>I am then building a link in the view as follows -</p> <pre><code>@Html.ActionLink("Test Link", "TestRoute", new { DateFrom = new DateTime(2006, 02, 16), DateTo = new DateTime(2008, 04, 22) }) </code></pre> <p>Which when rendered, outputs this URL -</p> <pre><code>/test/02/16/2006%2000%3a00%3a00/04/22/2008%2000%3a00%3a00 </code></pre> <p>As you can see, the framework has called <code>ToString()</code> on the <code>DateTime</code> parameters and then encoded the result.</p> <p>I would like to <strong>format the DateTime route parameters so they are output as "yyyy-MM-dd"</strong>. </p> <p>Obviously I can specify the format when building the Action Link like so -</p> <pre><code>@Html.ActionLink("Test Link", "TestRoute", new { DateFrom = new DateTime(2006, 02, 16).ToString("yyyy-MM-dd"), DateTo = new DateTime(2008, 04, 22).ToString("yyyy-MM-dd") }) </code></pre> <p>However we know this is messy, cumbersome and not DRY.</p> <p>I have tried using <code>[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]</code> attribute on the properties in the model hoping this was the answer, however it seems these are only respected when building editor forms.</p> <p>FYI, if I manually type the <code>DateTime</code> parameters in the URL in my browser (e.g. /test/2006-02-16/2008-04-22) the parameters are correctly parsed, so it's just a case of getting them formatted how I want.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload