How To: Clean Up ASP.NET JavaScript Tags

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:

5-4-2009 6-20-48 PM

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:

5-4-2009 7-10-04 PM

 

Hope this helps!

-Ira

kick it on DotNetKicks.com

Tags: , , , , ,

ASP.NET | ASP.NET | C# | JavaScript | C# | JavaScript

Comments

5/17/2009 10:26:30 PM #

Chris

Hey, just wanted to say thank you for responding to my question on your original post regarding cleaning up the head tag using control adapters. Trying to properly format JS was driving me crazy. Good stuff! Thanks again!

Chris United States

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Me

IraIra
I'm just another developer from Florida.

 

Sponsors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

All code samples on this website are free for download, use, and modification with no warranty nor any implied warranty. Liscensed by:

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 United States License.