Reputation: 2053
In C# ASP.NET I am adding a class to an <input>
using:
myInput.Attributes.Add("class","myClass");
At some point I would like to remove the added class (not all classes). Is there an equivalent along the lines of:
myInput.Attributes.Remove("class","myClass");
.Remove()
seems to only accept a key (no pair value). Thank you!
Upvotes: 4
Views: 7625
Reputation: 5672
I got inspired by Odeds post and created these two extension methods for you to elaborate with;
public static void AddCssClass(this WebControl control, params string[] args)
{
List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
List<string> classesToAdd = args.Where(x => !classes.Contains(x)).ToList<string>();
classes.AddRange(classesToAdd);
control.CssClass = String.Join(" ", classes);
}
public static void RemoveCssClass(this WebControl control, params string[] args)
{
List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
classes = classes.Where(x => !args.Contains(x)).ToList<string>();
control.CssClass = String.Join(" ", classes);
}
The methods are simply used to add or remove CSS classes from WebControls (from where Buttons, Labels, Panels etc. all inherits) like myButton.AddCssClass("class1", "class2");
or myButton.RemoveCssClass("class2");
.
It might very well be a bit overhead but managing the CssClass property can also be a bit of a hassle as you´re forced to handle the whitespaces on your own.
How many times haven´t you seen this one, for example?
string myCssClass = "class1";
myButton.CssClass += " " + myCssClass;
Please feel free to improve the methods! :)
Upvotes: 2
Reputation: 498914
There is nothing built in to manage multiple values in the attribute.
You will have to parse the list, remove the class name and update the attribute.
Something like (untested):
var classes = myInput.Attributes["class"].Split(' ');
var updated = classes.Where(x => x != "classtoremove").ToArray();
myInput.Attributes["class"] = string.Join(" ", updated);
Upvotes: 10