简体   繁体   中英

change css class in code behind

I'm trying to do something simple (in c#), but it doesn't work.

What I want to achieve: Change the text color of a label by changing the css class.

What I've got so far:

CSS:

.feedback {
    font-family: inherit;
    font-weight: normal;
    font-style: italic;
    font-size: 10pt;
}
.feedback.success {
    color: #71d398;
}
.feedback.fail {
  color: #75b9e6;
}

C#:

(...)
FeedbackLabel.Attributes.Add("Class", ".feedback.fail"); //one way I tried
FeedbackLabel.Text = "Error";
(...)
FeedbackLabel.CssClass = ".feedback.success"; //the other way I tried
FeedbackLabel.Text = "Done";
(...)

My problem: it gets the class, but it doesn't have any effect on the font. I even tried setting the .feedback.fail as default on the label and only change it in case of success. The result was that after start the .feedback.fail was active (including all settings), but when it should have changed to .feedback.success it just reset to application default. (But in debugging, I saw that it really got the right class..)

Do you have any idea what's interfering or what's wrong with my code above? Thanks in advance!

try this way FeedbackLabel.Attributes.Add("Class", "feedback fail") .

you shouldn't use . for specifying class attribute value for element

Unfortunately no answer here was working for me, so I decided to provide my own answer to this problem:

FeedbackLabel.Style["border"] = "1px solid black";

this would be an example on how to change individual style elements, but still not sure how to change a class.

Try this

FeedbackLabel.Attributes.Remove("class");

if(succcess)
  FeedbackLabel.Attributes.Add("class","feedback success");
else
  FeedbackLabel.Attributes.Add("class","feedback fail");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM