Displaying posts categorized under

Control your Javascript in ASP.NET

Adding each script only once

Lets face it - sometimes when we code we do mistakes. It would in our example of the JavaScript server control   be very easy to add the same script twice. It might not look that easy to do that mistake when just looking at the very simple example we have gotten so far – but in [...]

Step 4: Using the JavaScriptServe control (and download solution)

Lets now use the control we created in step 3 :
Apart from referencing the javascriptserve.dll we just set page1.aspx too look like this:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="page1.aspx.cs" Inherits="page1" Title="Page 1" %>
<%@ Register TagPrefix="includer" Namespace="JavaScriptServe" Assembly="JavaScriptServe" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<includer:JSIncludeControl ID="whatever" runat="server">
<includeFiles>
<includer:IncludeFile Path="scripts/hello.js" />
</includeFiles>
</includer:JSIncludeControl>

This one includes the javascript hello.js

Test to click <a href="javascript:Hello();">here</a>
</asp:Content>

And page2.aspx:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" [...]

Step 3: Render to page header

As explained in step 2 we want to render the script src tags into the page:s <header> part. And be able to do it from wothin the specific page:s contentplaceholders.  
I have developed a control for that – JSIncludeControl and it uses some of the techniques described in these articles:

Server control – custom collection with innercontent 
ASP.NET [...]

Step 2: Test case – control your Javascript

This testcase (solution is downloadable – in related article) is really simple and basic.

Master pages is used. The master page contains a single contentplaceholder

<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
[...]