如何增加超过1类ASP.NET中的元素? [英] How to add more than 1 class to an element in ASP.NET?

查看:110
本文介绍了如何增加超过1类ASP.NET中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想第二类编程添加到< TD方式> 在C#中的元素

I'm trying to programatically add a second class to a <td> element in C#.

我要添加类的元素已经有了一个类分配给它。

The element I want to add the class to already has a class assigned to it.

如果我做这样的事情。

myObject.CssClass = "MyClass";

它只是覆盖原来的类。

it simply overwrites the original class.

我想我可以做这样的事情。

I suppose I could do something like

myObject.CssClass += " MyClass";

但是这是丑陋的。

but that's ugly..

*免责声明 - 我讨厌做在C#中的HTML / CSS什么的想法,但我被分配到一个快速解决方案适用于已经恶魔code-基地。我没有看到任何一点在试图擦亮一个粪在这里,所以请不要拍我失望! : - )

*disclaimer - I hate the idea of doing anything with HTML/CSS in C#, but I've been assigned to apply a quick fix to an already diabolical code-base. I don't see any point in trying to 'polish a turd' here, so please don't shoot me down!! :-)

推荐答案

如果你不喜欢处理字符串连接,你可以创建一些辅助扩展方法。也许更code,但你可以添加和删除类没有看到发生的事情后。也许在code会看起来更清晰,你使用它。

If you don't like to deal with string concatenation you could create some helper extension methods. Maybe more code, but you can add and remove classes without seeing what goes behind. And maybe the code will look clearer where you use it.

myObject.AddCssClass("someclass");
myObject.RemoveCssClass("someclass");

---------

public static class WebHelper
{
    public static void AddCssClass(this WebControl control, string cssClass)
    {
        List<string> classes;
        if (!string.IsNullOrWhiteSpace(control.CssClass))
        {
            classes = control.CssClass.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (!classes.Contains(cssClass))
                classes.Add(cssClass);
        }
        else
        {
            classes = new List<string> {cssClass};
        }
        control.CssClass = string.Join(" ", classes.ToArray());
    }

    public static void RemoveCssClass(this WebControl control, string cssClass)
    {
        List<string> classes = new List<string>();
        if (!string.IsNullOrWhiteSpace(control.CssClass))
        {
            classes = control.CssClass.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
        }
        classes.Remove(cssClass);
        control.CssClass = string.Join(" ", classes.ToArray());
    }
}

这篇关于如何增加超过1类ASP.NET中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆