Introduction
The class presented in this article helps to write client side scripting inside .NET code.
Background
Sometimes you have to write JavaScript inside your code. The project I was doing, involved JavaScript to be written inside .NET code on a number of pages. Before, I used a string
object to create a script which is as follows:
string script = "<script lanugage=\"JavaScript\">";
script+= "alert('Hello world');";
script+= "</script>";
RegisterClientScriptBlock("myscript", script);
So, the class which I developed is very simple but helps the code to be a bit cleaner, and it's using StringBuilder
which is better when it comes to concatenating strings. Notice that we always have to begin script (<script lanugage= "Javascript">
) and end script (</script>
), where we can make a mistake while typing our code. Using this class, you don't have to type the above mentioned tags in your scripts.
Using the code
Following is an example to use the class which I have developed.
using vs.helpers;
ScriptHelper js = new ScriptHelper();
js.Add("alert('Hello world');");
js.Add("alert('This is an example');");
js.End();
RegisterClientScriptBlock("myscript", js.ToString());
Notice that you don't have to begin or end the <script>
tags. As mentioned earlier, ScriptHelper
is using StringBuilder
to concatenate strings, which is better when it comes to performance. Default language for the script is JavaScript but you can change the language while constructing ScriptHelper
object, by calling the constructor which takes one argument as string
which lets you specify the language of your script. A DLL for Visual Studio 2002 (1.0 framework) is included in the code. If anyone would like to use the code in 1.1, they can recompile the ScriptHelper
class in VS 2003. Sorry, I only have VS 2002 :).
Points of Interest
Today, while writing this article, it occurred to me that why not use a JavaScript interpreter in the Add
method. That way, whenever you add a script using Add
method, it can check that you are adding a valid JavaScript. So, you don't have to run the script in the browser in-order to find out that if it's syntactically or semantically right. It can check at compile time rather than run and fix. Please let me know if you have any suggestions to improve it further.