Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ActionLink generating NON-Restul URL AFTER adding constraints

I have a custom route without constraints that generates a Restful URL with an ActionLink.

Route -

 routes.MapRoute(
          "Blog", // Route name
          "Blog/{d}/{m}/{y}", // URL with parameters,
          new { controller = "Blog", action = "Retrieve" }

Generates -

   http://localhost:2875/Blog/12/1/2010

From -

<%=Html.ActionLink("Blog Entry - 12/01/2010", "Retrieve", "Blog", new { d = 12, m = 01, y = 2010 }, null)%>

If I add constraints like so.

            routes.MapRoute(
          "Blog", // Route name
          "Blog/{d}/{m}/{y}", // URL with parameters,
          new { controller = "Blog", action = "Retrieve" },
          new { d = @"\d{2}", m = @"\d{2}", y = @"\d{4}" }

It generates -

http://localhost:2875/Blog/Retrieve?d=12&m=1&y=2010

Extra information: it is added before the custom route.

Any ideas? Cheers

like image 800
brianstewey Avatar asked Dec 07 '25 15:12

brianstewey


2 Answers

I was working on the same issue while writing my blog.. In the end I realised that my Urls will have to use 1 digit month numbers.. change your route definition to this, and it will work:

routes.MapRoute(
   "Blog", // Route name
   "Blog/{d}/{m}/{y}", // URL with parameters,
   new { controller = "Blog", action = "Retrieve" },
   new { d = @"\d{1,2}", m = @"\d{1,2}", y = @"\d{4}" }

Or you can pass 2 digit strings as your day/month route values.. but you might miss this in some places and have dead links, so I'd recommend the route constraints fix..

If you DO find a workaround - drop me a mail pls ^_^

like image 151
Artiom Chilaru Avatar answered Dec 10 '25 05:12

Artiom Chilaru


Artiom is essentially right. Since your ActionLink code specifies single digit integers in the route values, the single digit fails against your constraint. So, you can either change the constraint as Artiom suggests, or slightly modify the ActionLink code so the route values are "strings" (in double quotes):

Html.ActionLink("Blog Entry - 12/01/2010", "Retrieve", "Blog", new { d = "12", m = "01", y = "2010" }, null)

like image 44
Crispy Avatar answered Dec 10 '25 05:12

Crispy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!