Chuck Conway

In The craft

ASP.NET: Add JavaScript in with Literal Control

January 13, 2005 · 1 minute read

This entry was posted on Thursday, January 13th, 2005 at 12:22 pm.

I’ve seen different ways of dynamically adding JavaScript through a code behind in ASP.NET. The problem is all the methods provided by .NET render the JavaScript right after the opening form tag or right before the close of the form tag.

I prefer to have my JavaScript in the head of the HTML page. The solution is simple: add a Literal control.

<style type="text/css" media="screen">@import url(/web/20061027200551im_/http://www.chuckknows.com/index.css);</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<asp:literal id="ltTest" runat="server"></asp:literal>

You may have to manually add the Literal control in the Code Behind:

protected System.Web.UI.WebControls.Literal ltTest;

Happy Coding!