Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect Route getting picked up and ActionLink is generating wrong hyperlink

I am new to ASP.NET MVC3.

I have configured some routes in Global.asax, against which I am generating some hyperlinks using @Html.ActionLink helper method.

All of the links are getting correctly rendered except the top one in the below code:

Global.asax

routes.MapRoute(
    null,
    "Section/{Page}/{SubPage}/{DetailPageName}",
    new { controller = "Base" }
    );

routes.MapRoute(
    null,
    "Section/{Page}/{SubPage}",
    new { controller = "Base", action = "SubPage" }
    );

routes.MapRoute(
    null,
    "Section/{Page}",
    new { controller ="Base", action="LandingPage"}
    );

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}", // URL with parameters
    new { controller = "Base", action = "Index" } // Parameter defaults
    );

ActionLink code

@Html.ActionLink(@subPages.LinkedPageName, "DetailPage",
    new {
        Controller = "Base",
        Page = @ViewBag.PageName,
        SubPage = @Model.SubPageName,
        DetailPageName = subPages.LinkedPageName
    })

The above should pick the top route i.e.:

routes.MapRoute(
    null,
    "Section/{Page}/{SubPage}/{DetailPageName}",
    new { controller = "Base" }
    );

But it is picking the default route!

like image 750
Deepak Pathak Avatar asked May 17 '12 10:05

Deepak Pathak


1 Answers

In this route definition:

routes.MapRoute(
    null,
    "Section/{Page}/{SubPage}/{DetailPageName}",
    new { controller = "Base" }
    );

The following conditions must be satisfied in order for the route to match:

  1. If there is a controller parameter passed into ActionLink then its value must be Base
  2. The Page parameter must be specified and must be non-empty because it has no default value
  3. The SubPage parameter must be specified and must be non-empty because it has no default value
  4. The DetailPageName parameter must be specified and must be non-empty because it has no default value

So in this call to ActionLink:

@Html.ActionLink(@subPages.LinkedPageName, "DetailPage",
    new {
        Controller = "Base",
        Page = @ViewBag.PageName,
        SubPage = @Model.SubPageName,
        DetailPageName = subPages.LinkedPageName
    })

Condition #1 is clearly satisfied. But conditions #2, #3, and #4 might not be satisfied because their values might be null.

And because you state that the route that ends up matching is the default route, I suspect that the Page parameter is null or empty. that is, @ViewBag.PageName is returning a null or empty value.

Check in your code (perhaps in the debugger or print it out in the view) to see whether the PageName property has a value.

like image 140
Eilon Avatar answered Oct 10 '22 14:10

Eilon