Can I make ASP.NET MVC Html.RouteLink() return a url for my home page without an ID?
-
20-08-2019 - |
Question
I've got a single route in my Global.asax.vb
page like this...
Shared Sub RegisterRoutes(ByVal routes As RouteCollection) routes.IgnoreRoute("{resource}.axd/{*pathInfo}") routes.MapRoute( _ "IdOnly", _ "{id}", _ New With {.controller = "Page", _ .action = "Details", _ .id = "7"} _ ) End Sub
That id
is for my home page. It's displayed when someone navigates to my: http://example.com/
But, this also works: http://example.com/7
I'd like to have no links anywhere on my site to the address with id
of 7. But, the Html.RouteLink()
function generates those.
For a view Model that's a child of the home page…
<%=Html.RouteLink(Model.Parent.Title, _
"IdOnly", _
New With {.id = Model.Parent.Id})%>
…generates the following anchor tag:
<a href="/7">Home</a>
How can I override the href
generated by the Html.RouteLink()
function for my home page?
Solution
Add a new route before your "IdOnly" route for the home page:
routes.MapRoute( _
"HomePage", _
"", _
New With {.controller = "Page", _
.action = "Details", _
.id = "7"} _
)
RouteLink
will use the first matched mapping in the routing table to generate the link.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow