Search code examples
c#asp.netdotnetnukehtml-encodehtmlgenericcontrol

How to prevent HtmlGenericControl from html-encoding content?


I'm writing an asp.net site (actually, a DotNetNuke module), using C#. From code-behind, I'm trying to create a <script> tag where I set a required js variable, then append it to the HMTL <head>. The js var is a (literal) array of relative urls for image files. Since the array contains strings, each item must be enclosed in quotes.

The problem is, the string between <script> and </script> is being automatically HtmlEncoded somewhere, so the quotes around each array item are being replaced with &quot;. That seems to take place when the HtmlGenericControl is rendered. Could DotNetNuke be the culprit? Could someone suggest a workaround?

My current code (running from Page_Load handler in my control):

HtmlGenericControl PreviewDataScriptTag = new HtmlGenericControl("script");
PreviewDataScriptTag.Attributes.Add("type", "text/javascript");
StringBuilder PreviewDataScriptCode = new StringBuilder();
PreviewDataScriptCode.Append("var preview_imgs = [");
string pathPrefix = @"""";
string pathSuffix = @""",";
foreach (string path in this.DocPreviewImages)
{
    PreviewDataScriptCode.Append(pathPrefix + PreviewUrlBase + Path.GetFileName(path) + pathSuffix);
}
// Remove last comma from js code
PreviewDataScriptCode.Remove(PreviewDataScriptCode.Length-1, 1);
PreviewDataScriptCode.Append("];");
PreviewDataScriptTag.InnerText = PreviewDataScriptCode.ToString();
Page.Header.Controls.Add(PreviewDataScriptTag);

Solution

  • Look at using the InnerHtml property of the node, not the InnerText property.

    The InnerHtml property does not automatically encode special characters to and from HTML entities. HTML entities allow you to display special characters, such as the < character, that a browser would ordinarily interpret as having special meaning. The < character would be interpreted as the start of a tag and is not displayed on the page. To display the < character, you would need to use the entity <.