I am trying to set my css theme based on a Request.QueryString variable. My code for selecting which Css theme to use is in a Function, however the function is getting rendered as output instead of getting evaluated and the output being rendered.
Using <%= GetCssTheme() %> makes it render as
<link href="Content/<%= GetCssTheme() %>.css" rel="Stylesheet">
however if I use <%= "" + GetCssTheme() %> it gets correctly rendered as
<link href="Content/ThemeA.css" rel="Stylesheet">
Here’s a small sample that illustrates the problem:
<%@ Page Language="vb" %>
<script language="vbscript" runat="server">
Public Function GetCssTheme() As String
Select Case Request.QueryString("SomeValue")
Case 2
Return "ThemeB"
Case 3
Return "ThemeC"
Case Else
Return "ThemeA"
End Select
End Function
</script>
<html>
<head runat="server">
<link href="Content/<%= GetCssTheme() %>.css" rel="Stylesheet" />
</head>
<body>
Test
</body>
</html>
Why do I need to specify a blank string in front of my function name for it to work?
I have tried various other methods too:
-
Using single quotes instead of double quotes
-
Using
<%= GetCssTheme().ToString() %> -
Using
<% Response.Write(GetCssTheme()) %> -
Using
<%
Dim s as String
s = GetCssTheme()
Response.Write(s)
%>
All of these incorrectly render the ASP.Net code itself instead of evaluating it and outputting the result.
The only thing I tried that does actually work is using in-line code instead of calling the function, or add a blank string to the function call.
The issue is because of the runat=”server” on your head tag. If you take it away the code will work just fine. This seems to be an old issue…
This URL shows the problem much like our dialog has been on this question, but has no cause.
http://geekswithblogs.net/mnf/archive/2007/11/14/code-render-blocks-not-always-work-inside-server-controls.aspx
So, if you don’t need the runat=”server” on your head tag, that will fix the issues…alternatively, if you do, you can always place the LINK tag at the start of the body which is not ideal.
I’ll continue to look, but I think this is either a side effect of other functionality or it is a bug in ASP.NET.
UPDATE:
I found this other SO question which specifies the cause. –
Inline code in head tag – ASP.NET