Incorrect route search and ActionLink generates the wrong hyperlink

I am new to ASP.NET MVC3.

I set up several routes in Global.asax against which I generate some hyperlinks using the @ Html.ActionLink helper method.

All links get the correct visualization, except for the top one in the code below:

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 choose the top route ie:

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

But he chooses the default route!

+6
source share
1 answer

In this route definition:

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

To match the route, the following conditions must be met:

  • If the controller parameter is passed to ActionLink , then its value must be Base
  • The Page parameter must be specified and must be nonempty because it does not have a default value
  • The SubPage parameter must be specified and must be nonempty because it does not have a default value
  • The DetailPageName parameter must be specified and must be nonempty because it does not have a default value

So, in this ActionLink call:

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

Condition No. 1 is clearly fulfilled. But conditions # 2, # 3 and # 4 may not be fulfilled, because their values ​​may be zero.

And since you are claiming that a route that ends in a match is the default route, I suspect that the Page parameter is empty or empty. i.e. @ViewBag.PageName returns a @ViewBag.PageName or empty value.

Check your code (possibly in a debugger or print it in a view) to see if the PageName property PageName value.

+2
source

Source: https://habr.com/ru/post/915978/


All Articles