asp.netroutesanchorasp.net-4.0webforms-routing

Routing to an anchor on another page


I am using Web Forms Routing in ASP.NET 4 and I am trying to route to a specific location on a page. On that page I have an element like <div id="3"> and I'd like to jump to this anchor from another page. For this purpose I have defined a Route in global.asax:

RouteTable.Routes.MapPageRoute("MyRoute", "Path/SubPath/{PageAnchor}",
    "~/MyPage.aspx", true, new RouteValueDictionary { { "PageAnchor", null } });

The HyperLink to link to that page and the anchor "3" is defined this way in markup:

<asp:HyperLink ID="HyperLink1" runat="server"
    NavigateUrl="<%$ RouteUrl:RouteName=MyRoute,PageAnchor=#3 %>">
    Link</asp:HyperLink>

The problem with the generated link is that the # character in the URL gets encoded by %23 this way: http://localhost:1234/Path/SubPath/%233 so that I reach the target page but not at the specified anchor.

Is there a way to avoid this unwished URL-encoding? Or any other way to route to an anchor?

Thank you in advance!


Solution

  • Anchors are not supported with ASP.NET's routing feature. Routing is designed to support only the part of the URL after the application's path and before the anchor.

    I suggest adding an event handler (e.g. Page_Load) and in that event handler generate the URL, append the anchor, and set the value on the HyperLink control.

    Of course, in most cases with Web Forms routing it's easiest to just set the URL manually to whatever you want. This is a nice option when the URL is not complex and is unlikely to change.