ASP.NET automatically converts & to &

Jakob Gade picture Jakob Gade · Dec 6, 2012 · Viewed 15.1k times · Source

Minor issue, but it's driving me nuts nonetheless.

I'm building a url for a <script> tag include to be rendered on an ASP.NET page, something like this:

<script src='<%= string.Format("http://example.com/page.aspx?a={0}&b={1}&c={2:0.00}", A, B, C)%>' type='text/javascript'></script>

Problem is when this is rendered, the & characters are replaced with &amp;:

<script src='http://example.com/page.aspx?a=xxx&amp;b=zzz&amp;c=123.45' type='text/javascript'></script>

I was expecting this, obviously:

<script src='http://example.com/page.aspx?a=xxx&b=zzz&c=123.45' type='text/javascript'></script>

However, if I render the url directly, outside the <script> tag, it looks ok! Just doing

<%= string.Format("http://example.com/page.aspx?a={0}&b={1}&c={2:0.00}", A, B, C) %>

Renders this:

http://example.com/page.aspx?a=xxx&b=zzz&c=123.45

What gives? And how do I stop this madness? My OCD can't take it!

Answer

Michael Richardson picture Michael Richardson · Jan 5, 2013

As @Falkon and @AVD have said, ASP.NET is automatically doing the "right" thing in the <script> tag. See the w3c recommendation - C.12. Using Ampersands in Attribute Values (and Elsewhere)

In order to ensure that documents are compatible with historical HTML user agents and XML-based user agents, ampersands used in a document that are to be treated as literal characters must be expressed themselves as an entity reference (e.g. "&amp;").

I'm not entirely sure why ASP.NET doesn't do the same thing in the rest of the page (could be any number of good reasons), but at least it's correcting the ampersand in the script tag. Conclusion: While you may be cursing ASP.NET for "scrambling" your url, you may want to thank it instead for helping your webpage be standards compliant.