MVC3: Why Html.Action does not generate the expected URL

I have a "Projects" controller and a "Dashboard" action which takes a parameter named "accountID".

 public ActionResult Dashboard(String accountID)
 {
     return View();
 }

I have a route defined as follows:

routes.MapRoute(
    "ProjectsHome",
    "{accountID}/projects",
    new { controller = "Projects", action = "Dashboard" }
);

The idea is to have an URL like /1111/projects where 1111 represents the accountID. The URL will then execute the Dashboard action of the Projects controller.

The issue which I am facing is that @Html.ActionLink("Projects", "Dashboard", "Projects", new { accountID = "1111" }, null) generates an URL like /Projects/Dashboard?accountID=1111 and I was expecting something like /1111/projects

My workaround is to use @Url.RouteUrl("ProjectsHome", new { accountID = "1111"}), but I was wondering why the Html.ActionLink does not pick the route I defined and formats the URL accordingly?

Another interesting fact is that in one of the controller's code I have something like return RedirectToAction("Dashboard", "Projects", new { accountID = newAccount.ID }); which builds the URL as I expected.

Note: I have no other routes defined except the generic "catch-all" one. I use ASP.NET MVC3.

Answers


The only way I've been able to replicate the result you're getting is by placing the "ProjectsHome" route below the generic "catch-all" route. When I had it placed above the generic route the ActionLink generated the URL in the form you wanted.

The MVC routing engine scans the route table until it finds one that it can match, meaning it can never reach a defined route that is after the catch-all.


the map route needs to be defined like this -

routes.MapRoute( "ProjectsHome", "{accountID}/projects", new { controller = "Projects", action = "Dashboard", accountID = UrlParameter.Optional } );

you missed to define the accountID in map route.


Need Your Help

Unable to convert mupdf into static library on iOS

ios xcode static-libraries mupdf

I am trying to convert mupdf (latest source) to a static library. I cloned the source and am able to run it on my iPad. However I am unable to compile it into a static library. I followed the

How can i use bootstrap to make a column that spans over other rows beneath it?

jquery html css twitter-bootstrap

I have a website with a 3 column layout, and I want my middle column to have a different height than the side columns, then I have a second row of 2 columns that I have col-pull-left and col-push-r...