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 &
:
<script src='http://example.com/page.aspx?a=xxx&b=zzz&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!
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. "
&
").
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.
Maybe MvcHtmlString.Create()
or Html.Raw()
?
<script src='<%= MvcHtmlString.Create("http://example.com/page.aspx?a={0}&b={1}&c={2:0.00}", A, B, C)%>' type='text/javascript'></script>
or
<script src='<%= Html.Raw("http://example.com/page.aspx?a={0}&b={1}&c={2:0.00}", A, B, C)%>' type='text/javascript'></script>
I can work it out. I just make a method:
public void BuildUrl(String baseUrl = "", String data = "")
{
Response.Write(baseUrl + data);
}
and use it in my html page like this:
<button type="button" class="btn_new" ref="<% this.BuildUrl(this.BaseUrl + "Master/Tanker_Edit.aspx?", "type=new&unique_id=" + Session.SessionID); %>">New</button>
The result:
<button type="button" class="btn_new" ref="http://kideco.local/Master/Tanker_Edit.aspx? type=new&unique_id=emxw1pkpnwcxpn1cl2cf04zv">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With