在运行时将 class 添加到 html 标签 asp net

add class to html label at runtime asp net

我从事 asp.NET,使用 C# 在服务器端编码。

在"view"部分,我的body中只有一个标签,是服务器端:

HTML

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

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

CSS

.label_error {
    color : red;
}

.label_success {
    color : green;
}

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

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" */
}

我的问题:

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

谁能告诉我解决方案?

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

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

html_label_1.CssClass = "label_error"