Injecting javascript into asp.net via code

Microsoft has a great MSDN article on using javascript along asp.net, but they didn’t mention a technique I like to use, put it in a Literal control.  While there are many ways to add javascript to a page, I find putting the javascript in a literal much less stressful. Using a Literal control placeholder is also a good way to add messaging to a page after postback, but we’re just going to look at adding javascript.

Let’s take a simple example.  Say you’ve got a comment form that you want to auto close, or reload after the form was posted.  Below is a simple single file style asp.net page with a simple javascript function that reloads this page.

<%@ Page Language="C#" %>

<script runat="server">
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {

    }
}

/////////////////////////////////////////////////////////////////////////////// 
/// Do stuff with the form data, then refresh page using javascript
protected void submitComments(object sender, EventArgs e)
{

    try
    {
	//
	// do stuff here
	//

	// set javascript timer to reload page afer 3 seconds
	js_target.Text = "setTimeout('reload()', 3000);";

    }
    catch (Exception exc)
    {
        Response.Write( "ERROR : " + exc.Message );
    }
}
</script>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
	<title>Comments</title>
	<script type="text/javascript">
	// page reload helper
	function reload() {
		document.location.replace( document.location );
	}
	</script>
</head>
<body>

<form id="form1" runat="server" method="post">

<script type="text/javascript"><asp:Literal runat="server" id="js_target" /></script>

	Comments
	<asp:TextBox runat="server" ID="comment_box" Width="200" />
	<br><br>

	Your name
	<asp:TextBox runat="server" ID="fullname" Width="200" />
	<br><br>
	<asp:Button runat="server" ID="submit_btn" onclick="submitComment" Text="submit" />

</form>
</body>
</html>

If you look just under the form tag you’ll see the key to this technique, an asp literal wrapped by an open and close script tag.

<script type="text/javascript"><asp:Literal runat="server" id="js_target" /></script>

When you load your page and view the source you’ll just see an empty script tag, so it shouldn’t interfere with the execution or rendering of your page.

The last part of this technique is simple, in your server code just set your Literal control’s .Text value to your javascript code. In this case when I post my comment form, after handling the input data I display a thank you message, then set some javascript to reload the page.

ltl_js.Text = "setTimeout('reload()', 3000);";

That’s all there is to it. Drop a literal in an empty script block and BAM!, you have an easy way to add javascript to your asp.net page.

How to customize WebForm1.aspx in Visual Studio 2003

I finally found out where to customize the WebForm1.aspx template for Visual Studio 03.

C:Program FilesMicrosoft Visual Studio .NET 2003VC#VC#WizardsCSharpAddWebFormWizTemplates1033WebForm1.aspx

Now I don’t have to keep removing all those extra tags that Visual Studio likes to add. MS_POSITIONING?!?! Am I the only programmer who knows HTML and CSS?

Of course, you could just read this article and build your own custom form wizard.