7

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);
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • 1
    I recommend using lower-cased names for your variables. This is confusing to read. –  Aug 20 '11 at 01:52
  • Thanks for the tip. I'm not really used to .net, and started using upper-case for everything after realizing .net developers tend to upper-case *object property names*. I guess it's a case of over correction! – bfavaretto Aug 20 '11 at 03:44

1 Answers1

16

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 <.