Printing a public string variable to a page in ASP.NET
Overlooking something basic here but I am trying to set a v开发者_如何转开发ariable and have it print 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=<%=myVariable %>" />
It seems to have something to do with the quotes as this works when I take it outside of the href. I find that it works fine if I place a string in the code segement.
This works, but isn't what I want:
<link rel="stylesheet" type="text/css" href="/css/main.css?v=<%="40"%>" />
What is the logic behind this behavior and what do I need to do to make it work? I would also settle for a more elegant method of doing this.
You need to single quote the html attribute like so:
<link rel="stylesheet" type="text/css" href='/css/main.css?v=<%=myVariable%>' />
I use this all the time especially within 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 the link tag in the head section of your aspx page then check out this question for more info: Problem in Expression tag to bind string variable
Why don't you just do like this:
<link rel="stylesheet" type="text/css" <%= ("href='/css/main.css?v=" + myVariable + "'") %> />
I actually had this same issue today and solved it by using a custom code expression builder.
Your code will look something like this:
<link rel="stylesheet" type="text/css" href="/css/main.css?v=<%$ Code:myVariable%>" />
A 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 of a server side control.
It was really easy to implement.
Here's 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 was all I did to get it to work.
Try this:
<link rel="stylesheet" type="text/css" href=<%="/css/main.css?v="+myVariable %> />
AFAIK, the whole property must be a code block, like:
href='<%= "css/main.css?v=" + myVariable %>'
精彩评论