I'm trying to programatically add a second clas开发者_C百科s to a <td>
element in C#.
The element I want to add the class to already has a class assigned to it.
If I do something like
myObject.CssClass = "MyClass";
it simply overwrites the original class.
I suppose I could do something like
myObject.CssClass += " MyClass";
but that's ugly..
*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!! :-)
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());
}
}
精彩评论