Friday, April 13, 2018

Easily Add/Remove CSS classes on a HTML Server Side Control

Today I needed to add a CSS class to a html element from the code behind on the server.  The html element already had one CSS class but I needed to add and remove another CSS class as needed (I wanted to add and remove an error class when a text box had an invalid value).  I figured there was some built in ability to do this in asp.net already but I was wrong.  The current support for changing the CSS class attribute from the server looks like this:
 
HtmlGenericControl myControl = new HtmlGenericControl();
myControl.Attributes["class"] = "MyCSSClassName";
The problem is doing this will overwrite any existing CSS classes that were set in the markup directly.  The solution is not hard, you just need to do this:
 
HtmlGenericControl myControl = new HtmlGenericControl();
myControl.Attributes["class"] = "MyCSSClassName MyCSSErrorClassName";
The string set in the “class” attribute just needs to follow the standard CSS format for multiple classes on a single element.  Updating that string every time I needed to add or remove a class would get old quick so I decided to use an extension method to make life easier.  Actually I created three methods:  CSSAddClass, CSSHasClass, and CSSRemoveClass.  Using these methods you can easily add and remove my CSS error class as needed.  Here is the code for my extension methods:
 
public static class HTMLExtensions
    {
        public static void CSSAddClass(this HtmlGenericControl ctrl, string className)
        {
            var classes = ctrl.Attributes["class"];

            if (string.IsNullOrEmpty(classes))
            {
                ctrl.Attributes["class"] = className;
            }
            else
            {
                var classList = classes.Trim().Split(' ').ToList();
                if (!classList.Contains(className))
                {
                    classList.Add(className);
                    ctrl.Attributes["class"] = classList.Aggregate((current, next) => string.Format("{0} {1}", current, next));
                }
            }
        }

        public static bool CSSHasClass(this HtmlGenericControl ctrl, string className)
        {
            var classes = ctrl.Attributes["class"];

            if (string.IsNullOrEmpty(classes))
            {
                return false;
            }
            else
            {
                var classList = classes.Trim().Split(' ').ToList();
                return classList.Contains(className);
            }
        }

        public static void CSSRemoveClass(this HtmlGenericControl ctrl, string className)
        {
            var classes = ctrl.Attributes["class"];

            if (!string.IsNullOrEmpty(classes))
            {
                var classList = classes.Trim().Split(' ').ToList();
                if (!classList.Contains(className))
                {
                    classList.Remove(className);
                    ctrl.Attributes["class"] = classList.Aggregate((current, next) => string.Format("{0} {1}", current, next));
                }
            }
        }
    }
 
From my code behind I can now just write code like this when I need to change the CSS class of an element:
 
this.labTest.CSSAddClass("MyCSSErrorClassName");
 
The extension code is extending html generic control only because that is what I needed it for but you can easily change it to work with other web controls that have the attributes property.

Source : http://www.frankwisniewski.net/2013/04/17/easily-addremove-css-classes-on-a-html-server-side-control/

No comments:

Post a Comment