K M
K M

Reputation: 55

Dynamically naming classes in aspx

My goal is to create a series of clickable buttons that each have a unique image. Currently these image are stored as classes in CSS and this shows up fine - and I can call them by GImg EGCImg1, GImg EGCImg2... Etc. However, I want to make this dynamic so I can set X number of buttons instead of copy/pasting the code (which I hate to do). Below are the only 'useful' resources I was able to find, but unfortunately their suggestions didn't work for me.

http://forums.asp.net/t/1619813.aspx/1

http://www.codeproject.com/Articles/14033/Dynamic-CSS-Styling-in-ASP-NET-A-Flexible-Approach

So basically the below code, when I manually set the {0} will work perfectly. They'll even properly list along if I set this value - just all with the same image.

Only <% string.Format("GImg EGCImg{0}", i); %> is broken.

<% for (int i = 0; i < 3; i++){ %>
  <li>
     <label class="baseTemplate">
        <b>
           <%=Html.RadioButtonFor(x => x.Input.MailTemplate, i)%>
        </b><span class="<% string.Format("GImg EGCImg{0}", i); %>"><span class="CheckMark"/>
            </span>
      </label>
   </li><% } %>

Any and all suggestions are welcome, Thanks!

Upvotes: 0

Views: 73

Answers (3)

JabberwockyDecompiler
JabberwockyDecompiler

Reputation: 3390

You can use the Attributes.Add and Attributes.Remove

aspx file

<span id="YourContainer" runat="server">Report Type</span>

c# code behind

YourContainer.Attributes.Add("class", "active");
YourContainer.Attributes.Remove("class");

Upvotes: 0

Darren Wainwright
Darren Wainwright

Reputation: 30737

You're missing the = after <%

Also, you can do the following:

<span class="GImg EGCImg<%= i.ToString() %>"><span class="CheckMark"/></span>

Rather than using the String.Format method, just append the i at the end of your class. Little less overhead too.

The = is like saying Response.Write

Upvotes: 1

AlbertVo
AlbertVo

Reputation: 772

one option is to use inline css, so instead of class="classname", you would do style="background: red;". This is the easiest way without changing too much of your code. You can also generate dynamic css in the head, or link externally to a generated css file.

Upvotes: 1

Related Questions