Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET automatically converts & to &

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!

like image 674
Jakob Gade Avatar asked Dec 06 '12 06:12

Jakob Gade


3 Answers

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.

like image 133
Michael Richardson Avatar answered Nov 02 '22 20:11

Michael Richardson


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>
like image 3
Kaizen Programmer Avatar answered Nov 02 '22 20:11

Kaizen Programmer


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">
like image 1
Situs Panesse Avatar answered Nov 02 '22 20:11

Situs Panesse