I am using the following code to add a series of calls to the body parameter of a page in asp.net:
uxBodyTag.Attributes["onbeforeunload"] +=
"ajaxRequest('UnlockQuery.ashx?QueryID=" + queryId.ToString() +
"&UserID=" + Session["UserID"].ToString() + "');";
This is being rendered as:
<body id="uxBodyTag" onbeforeunload=
"ajaxRequest('UnlockQuery.ashx?QueryID=176&UserID=11648');">
The & means my ashx page is not retrieving the correct variables - how can I stop asp.net from doing this?
EDIT:
Using Server.UrlEncode gives me the following:
<body id="uxBodyTag" onbeforeunload=
"ajaxRequest('UnlockQuery.ashx%3fQueryID%3d179%26UserID%3d11648')%3b">
Which is far worse.
In HTML the ampersand needs to be encoded, always, everywhere, also in attribute values (the contents of the
<script>
tag is the notable exception, obviously). ASP.NET does the right thing.Attribute values will be unencoded by the browser before it actually uses them. So your
onbeforeunload
attribute has a literal value of:while the HTML representation needs to have the
&
in place of the&
. The browser usually understands the ill-encoded version as well, but an SGML parser would complain about an unknown/invalid entity named&UserID
.The behaviour you are seeing with & encoded as & is the behaviour you want. By the time the text gets to your ajaxRequest function it will have been unencoded again and everything should be fine.