Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC: How do I get Html.ActionLink to render integer values properly?

I have an asp.net mvc application with a route similar to:

routes.MapRoute("Blog", 
    "{controller}/{action}/{year}/{month}/{day}/{friendlyName}",                          
    new { controller = "Blog", action = "Index", id = "", friendlyName="" }, 
    new { controller = @"[^\.]*", 
          year = @"\d{4}", 
          month = @"\d{2}", 
          day = @"\d{2}" }
);

My controller action method signature looks like:

public ActionResult Detail(int year, int month, int day, string friendlyName)
{ // Implementation... }

In my view, I'm doing something like:

<%= Html.ActionLink<BlogController>(item => item.Detail(blog.PostedOn.Year, blog.PostedOn.Month, blog.PostedOn.Day, blog.Slug), blog.Title) %>

While the url that is generated with ActionLink works, it uses query string variables rather than URL rewriting.

For example, it would produce /blog/detail/my-slug?year=2008&month=7&day=5 instead of /blog/detail/2008/07/05/my-slug

Is there a way to get the generic version of ActionLink to properly pad the integer values so that the url comes out as expected?

Thanks

Jim

like image 254
Jim Geurts Avatar asked Sep 28 '08 18:09

Jim Geurts


1 Answers

The fact that your parameters are integers has nothing to do with your problem. The route definition you want to be used isn't actually being used, which is why the generated URL is using query string parameters instead of building the structure you want.

Routes are evaluated top-down, so you likely have a more generic route definition that is satisfying your requested URL generation. Try moving the route you displayed in this post to the top of your route definitions, and you'll see that your generated link is as you'd expect. Then look into modifying your route definitions to either be more specific, or just move them around as necessary.

Debugging these types of scenarios can be a huge pain. I'd suggest downloading Phil Haack's route debugger, it will make your life a lot easier.

like image 101
Jonathan Carter Avatar answered Sep 28 '22 04:09

Jonathan Carter