Marking ASP.NET 2.0 Generated JavaScript as CDATA
Posted on Wed 01 November 2006 in ASP.NET
The following code example is a workaround for marking ASP.NET generated JavaScript as CDATA, which is required when serving XHTML ASP.NET 2.0 pages as application/xhtml+xml (see Serving the Correct MIME Type for XHTML using ASP.NET 2.0).
Place the following code in your master page:
protected override void Render(HtmlTextWriter writer)
{
StringWriter stwHtml = new StringWriter();
base.Render(new HtmlTextWriter(stwHtml));
String strHtml = stwHtml.ToString();
// Enclose ASP.NET generated client ECMAScript / JavaScript in CDATA Wrapper
Regex regScriptCDATA = new Regex("(<script\stype="text\/....script">(?:\s)*?)" + "(?:<!--\s)" + "((?:.|
)*?)" + "(?:// -->)" + "((?:\s)*?<\/script>)");
String strScriptCDATA = "$1" + "<!--//--><![CDATA[//><!--
" + "$2" + "
//--><!]]>" + "$3";
strHtml = regScriptCDATA.Replace(strHtml, strScriptCDATA);
writer.Write(strHtml);
}
You may need to add the following at the beginning of your master page code:
using System.IO;
using System.Text.RegularExpressions;