Printing a public string variable per page in ASP.NET

Looking back at something basic here, but I'm trying to set a variable and print it in several places on the page. code behind:

public string myVariable { get {return "40"; } } 

page:

 <link rel="stylesheet" type="text/css" href="/css/main.css?v=<%=myVariable%>" /> 

output:

 <link rel="stylesheet" type="text/css" href="/css/main.css?v=&lt;%=myVariable %>" /> 

Something seems to be connected with quotation marks as it works when I take it outside of href. I find it works fine if I put a line in code segregation.

This works, but this is not what I want:

 <link rel="stylesheet" type="text/css" href="/css/main.css?v=<%="40"%>" /> 

What is the logic of this behavior and what do I need to do to make it work? I would also agree on a more elegant way to do this.

+4
source share
5 answers

You need to digitize the html attribute like this:

 <link rel="stylesheet" type="text/css" href='/css/main.css?v=<%=myVariable%>' /> 

I use this all the time, especially in repeaters, when I want to create anchor tags

 <a href='PageToLinkTo.aspx?id=<%# DataBinder.Eval(Container.DataItem, "Id")%>'>Link Text</a> 

This will only work in the body of your aspx page. If you have a link tag in the title section of your aspx page, check out this question for more information: The problem is in the Expression tag for binding a string variable

+5
source

Why don't you just do this:

 <link rel="stylesheet" type="text/css" <%= ("href='/css/main.css?v=" + myVariable + "'") %> /> 
+4
source

I had the same problem today and it was solved using a custom code expression constructor .

Your code will look something like this:

 <link rel="stylesheet" type="text/css" href="/css/main.css?v=<%$ Code:myVariable%>" /> 

The good tutorial that I used can be found here , which I was able to modify to fit my application. This will also work if you need to add code inside the server side control.

It was really easy to implement.

Here is what I added to my web.config :

  <compilation debug="true"> <expressionBuilders> <add expressionPrefix="Code" type="CodeExpressionBuilder"/> </expressionBuilders> </compilation> 

And in my App_Code folder, I created ExpressionBuilder.vb :

 Imports Microsoft.VisualBasic Imports System.Web.Compilation Imports System.CodeDom <ExpressionPrefix("Code")> _ Public Class CodeExpressionBuilder Inherits ExpressionBuilder Public Overrides Function GetCodeExpression(ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, ByVal context As ExpressionBuilderContext) As CodeExpression Return New CodeSnippetExpression(entry.Expression) End Function End Class 

That is all I have done to make it work.

+2
source

AFAIK, the whole property must be a block of code, for example:

 href='<%= "css/main.css?v=" + myVariable %>' 
0
source

Try the following:

 <link rel="stylesheet" type="text/css" href=<%="/css/main.css?v="+myVariable %> /> 
0
source

All Articles