Monday, March 23, 2009

VB.NET 2008 - XML parser makes writing Javascript easy

Today I had the need to write some Javascript in an ASP.NET VB code-behind. I was about to do it the old way with quotes and ampersands and underscores.

And then I had a thought. VB in Visual Studio 2008 has a built-in XML parser. So all I have to do is start typing xml and the IDE will recognize it. So why not put the Javascript inside a CDATA tag in some XML and let VB take care of the rest?

It works! Here's an example...

Dim script = <xml>
<![CDATA[
alert("Hello World!");
]]>
</xml>

Response.Write(script.Value)


This makes it so easy to write Javascript in a code-behind, especially when you have a lot of Javascript to write.