by ira
4. May 2009 19:13
In April of '08, I wrote a post about cleaning up the ASP.NET head tag using control adapters. I've got some great feedback from it, and I'm glad that I'm not the only one that is horrified when looking at the source of an ASP.NET rendered web page. From the comments of that article I was recently asked how to clean up JavaScript tags. With the code from the project download of the article as-is, when I just slap some script tags in the head tag I get something that looks like this rendered:
However, sometimes you are adding JavaScript from your code behind. In this case I do it like this:
protected void Page_Load(object sender, EventArgs e)
{
string pageScript = @"function CallMeOnWindowLoad() {
alert('I have been called!');
}
window.onload = function() {
CallMeOnWindowLoad();
}
";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "LoadScript",
pageScript, true);
}
If you look, you can see where I'm using the string literal "@" to tell ASP.NET to render it exactly like I am putting it in. Take note of the CrLf after the final "}" of my script. This will break any new script or the end script tag to a new line. I also use the Page.ClientScript.RegisterScripBlock method. The arguments are very simple, but take note of the last argument. This boolean value tells ASP.NET to wrap the script inside of a "script" tag. Using this method will render it like this:
Hope this helps!
-Ira