Steven
Steven

Reputation: 19455

How do I "dynamically" add css class?

Inside my aspx file, I have the following html code inside an repeater: <div class="someItem ">.

Now, if Eval("Approved") == true, then I would like to add the class approved to the div.
So the new html would be <div class="someItem approved">.

I tried doing something like this:

<%# if(Eval("Approved")) approved %>

But that didn't work very well. Any ideas?

Upvotes: 0

Views: 6679

Answers (4)

Chris
Chris

Reputation: 6325

You can use an asp.net panel and control the action of it from the code behind. A panel renders as a DIV and you have access to it's CssClass during the runtime.

Upvotes: 0

Bhaskar
Bhaskar

Reputation: 10691

You can make the div a server control as -->

<div id="myDIV" class="myClass" runat="server"></div>.

Then you can directly access it from your code behind, as

myDIV.Attributes["class"] = "classOfYourChoice";

See this --> How to edit CSS style of a div using C# in .NET

Upvotes: 2

ant
ant

Reputation: 22948

maybe it would be better to consider this if the item is approved <div id="someItem"> and then add class approved if the eval of whatever is true ..

<div id="someItem" "<%# Eval("Approved") ? Response.Write("class=\"approved\"") : "" %>">

Upvotes: 1

Amr Elgarhy
Amr Elgarhy

Reputation: 69042

If can't work in databinding # line.

So you can work around this by something like this:

<%# isApproved = Convert.ToBoolean(Eval("Approved").ToString()) %>
<% if(isApproved){ %>
  <div class="someItem approved">
<%}%>

And don't forget to declare isApproved as protected in the code behind.

Also please take a look at this question:

Is it possible to use Data-Binding Expressions directly in markup to show/hide content?

Which may answer the most important part of your question.

Upvotes: 1

Related Questions