Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a public string variable to a page in ASP.NET

Tags:

c#

asp.net

Overlooking something basic here but I am trying to set a variable 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=&lt;%=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.

like image 962
LeRoy Avatar asked Dec 22 '22 13:12

LeRoy


1 Answers

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

like image 86
lomaxx Avatar answered Jan 22 '23 00:01

lomaxx