Search code examples
javascriptentitycode-behindreplace

ASP.NET entities breaks javascript in codebehind


I am doing the following in codebhind with a HyperLink control:

hlNonTerminal.Attributes["onclick"] = string.Format("highlightTokenUsage('{0}');", nonTerminal);

but the ' character is replaced by asp.net and the browser thus gets:

<a id="..." onclick="highlightTokenUsage(&#39;CITY&#39;);">CITY</a>

How can I turn this off or bypass it? This happens inside a user control, but the page which includes it has ValidateRequest="false".


Solution

  • The encoding mechanism is (probably) implemented right in the underlying Render method of the AttributeCollection class so overriding the server control and modifying the rendering logic will change that. However, I do strictly advise you not to do so, since the current implementation works fine.

    The <a id="..." onclick="highlightTokenUsage(&#39;CITY&#39;);">CITY</a> link you've shown us is perfectly valid. The &#39; code is decoded into ' character before invoking the highlightTokenUsage method, so it doesn't do any harm to you.

    BTW, please note that this kind of attribute manipulation through code behind (actually, mixing the HTML and JavaScript code) is against the "Unobtrusive Javascript".