css - 在运行时向 html 标签添加类 asp net

标签 css asp.net label

我在 asp.NET 上工作,使用 C# 在服务器端编码。

在“ View ”部分,我的 body 只有一个标签,它是服务器端:

HTML

<label runat="server" id="html_label_1"></label>

我想在运行时更改它的类。这是我的 2 个 CSS 类:

CSS

.label_error {
    color : red;
}

.label_success {
    color : green;
}

我在 C#(服务器端)中创建了 2 个函数,它们更改了这个标签的文本并且应该添加正确的类,如下所示:

C#

protected void displayError(object error) 
{
    string err = error.ToString();

    html_label_1.InnerText = err;
    /* this is where I want to toggle class to ".label_error" */
}

protected void displaySuccess(object success) 
{
    string succ = success.ToString();

    html_label_1.InnerText = succ;
    /* this is where I want to toggle class to ".label_success" */
}

我的问题:

我没有看到任何属性来设置我自己的类。当服务器端在 html_label_1 上按 [CTRL]+[SPACE] 时,我只看到 html_label_1.Style.Add(),但是这个方法需要一个带有样式的字符串,它不是我的目的。

谁能帮我找到解决方案?

最佳答案

尝试在后面的代码中使用以下内容:

html_label_1.Attributes.Add("class", "label_error");  

html_label_1.CssClass = "label_error"

关于css - 在运行时向 html 标签添加类 asp net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29842379/

相关文章:

javascript - CSS 不适用于书签

asp.net - 如何修复此页面的状态信息无效并且可能已损坏

c# - ASP.NET MVC 3 : IDepencyResolver is trying to get an implementation of IControllerFactory

matlab - 条形图中用标签代替颜色

indexing - Neo4j:标签索引中的 "ghost"节点抛出错误

javascript - 伪元素出现在焦点上但不在单击时出现

javascript - 如何在倒计时结束后显示图像?

jquery - 导航栏不起作用

javascript - 动态加载的用户控件中控件的单击事件未在 .js 文件中触发

qt - QLabel中的文本滚动(字幕)