ASP.Net HyperLink Control And Html Encoded Ampersand’s

I just ran into some odd behavior with the HyperLink control ASP.Net. Per the W3C, you’re supposed to HtmlEncode ampersands, using & instead of ‘&’ when building URLs in your HTML code. The reason is that the ‘&’ is assumed to be an entity reference. What’s nice is most web browsers can recover from this type of error, but if you want your site to pass validation, you need to use & instead.

So I hooked up all of our URLs to use this method, especially when we wrote out URLs in our C# classes. What I found odd was if I did this using a HyperLink control instead of an HtmlAnchor control, .NET would write the & out in the URL instead of using ‘&’. Naturally this broke our site as query string references weren’t parsed properly. The fix was to use an HtmlAnchor instead.

I’m not really sure why .NET does this or if there’s another workaround for it, but this solution worked for me. I’d be curious to know the reason behind the behavior though.

3 thoughts on “ASP.Net HyperLink Control And Html Encoded Ampersand’s

  1. Dave

    Hi Bill

    Just had this problem myself. After a bit of investigating it turns out that if you don’t use the TEXT property of the AspHyperlink, things work as expected:

    Does not work:

    This does work:
    This & That

  2. Dave

    Hmm your page removed my code!

    Anyway to clarify, don’t use the TEXT property of the hyperlink. Instead write out the text you need inside the opening and closing hyperlink tags.

  3. Bill

    Hah, sorry about that. Interesting that using the TEXT property does that. I’ll have to check it out as the solution I came up with had some not so good side effects.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.