2

I was wondering if it was possible to define and use a variable in your html using C# tags.

So for instance

<% String var = "simpleString"; %>
<link rel="stylesheet" type="text/css" href="style.css?v=<%Response.Write(var);%>" />

I have been trying to get something like this to work. When I write it like

<% String var = "pineapples"; Response.Write(var);%>

it works, but when I write them in separate tags it doesn't seem to read it as a variable.

2
  • It might be worth being clear on what it does do in that situation (ie say if it throws an error, displays that text literally, etc.). Sadly I've not done webforms for ages since I am more a razor man now so not sure how much help I can be. I do have a vague recollection though of always replacing the whole attribute value rather than just part of the it but not sure if that is a genuine useful memory or not. :) Commented Jul 17, 2015 at 9:02
  • With .Net Webforms and MVC razor templates that's possible. Commented Jul 17, 2015 at 9:02

1 Answer 1

3

var is a keyword in c# used to implicitly type a variable.

String is explicitly typed.

You have used both in your example:

String var = "simpleString";

You could change it to:

String var1 = "simpleString";

using your desired variable name above.

<% String var1 = "simpleString"; %>
<link rel="stylesheet" type="text/css" href="style.css?v=<%=var1%>" />

Also note that from mark-up you can use <%= %> to output rather than Response.Write.

Sign up to request clarification or add additional context in comments.

5 Comments

hi you wouldnt happen to know who to escape that. so <div> <%=var1%> outputs fine, but when its like href="style.css?v=<%=var1%>" it outputs href="style.css?v=<%=var1%>" instead of href="style.css?v=simpleString>". i know its because it sees it as string and not a variable, but how would i make it see it as a variable?
@Wim If I understand you correctly, try changing it to single quotes i.e. <link rel='stylesheet' type='text/css' href='style.css?v=<%=var1%>' />
see the problem is that inserting <%var1%> inside quotes is the problem. so when i make the variable, VS highlights it and says its unused. when i type the variable inside quotes it would not recognize it as a variable at all so in other words the statement that you gave me href='style.css?v=<%=var1%>' outputs the same as before. it outputs the var1 as a string instead of the value inside it
@Wim That is odd, I don't get that. Is it razor that you are using and not an .aspx?
im pretty sure. its a aspx file that i am editing, does that make a difference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.