Conditional JavaScript in ASP.Net

Now this is annoying me, I’m trying to take an existing classic ASP solution and convert it to ASP.Net 2.0 as a learning exercise. The problem is that I’m struggling to convert this –

<head>
<title>A Page</title>
<% if intCategoryID < 3 then %>
<script language="javaScript"
src="http://www.foo.com/foo.js"></script>
<% end if %>
</head>

So, I want to only include the JavaScript if a condition is met (in this case intCategoryID < 3). How do I achieve this in ASP.Net?? I have looked at an asp:literal tag to achieve this but Visual Web Developer suggests a literal cannot include child tags (the script tag itself). Can I add one programmatically from the codebehind?

I hope I can find a solution to this..

Posted in .Net. 3 Comments »

3 Responses to “Conditional JavaScript in ASP.Net”

  1. Mike Says:

    Did you ever find a solution to this?

  2. Adam Says:

    I think I did Mike. I’ll see if I can find something and post later on Today (hopefully).
    Edit: i’ll take a look at this next week.

  3. Adam Says:

    A simple approach (taken from here is something like this in your codebehind –

    
    if intCategoryID < 3 then
     dim si as new HtmlGenericControl
     si.TagName = "script"
     si.Attributes.Add("type", "javascript")
     si.Attributes.Add("src", "/hilite.js")
     Page.Header.Controls.Add(si)
    end if
    

    You could also use RegisterClientScriptInclude as detailed here


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: