views:

25

answers:

2

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!

A: 

Does this work?

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

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

If you place the # outside of the PageAnchor placeholder, you could avoid that value being decoded, and it seems like a cleaner way to do it, besides.

Jacob
This is exactly what I had tried before. But it has two issues: 1) If you simply enter the route URL without an anchor in the browser (`http://server/Path/SubPath`) you get a 404 since this isn't a valid route anymore. 2) The unwished URL encoding of the `#` still happens.
Slauma
+2  A: 

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.

Eilon
Hm, I was hoping for a declarative solution. Well, specifying the NavigateUrl in code-behind would be the last resort.
Slauma
I have done it now in code-behind. Thanks for your help!
Slauma