0

Is there an inbuilt ASP.Net or MVC3 function that generates a valid CSS class given a string. Tagbuilder seems to have one AddCssClass. However just wondering if there is anything else that takes a string and converts it to valid CSS Class name by converting invalid characters to valid ones?

As an example say I have a string "Test. Bad Class Name"

I was wondering if there was a helper function to convert this to "Test__Bad Class_Name" or some such thing.

MVC doesn't seem to generate bad IDs etc so I just wondered if it had something that did this so I was being consistent. I just thought it would be a common requirement.

3
  • What makes you think that TagBuilder.AddCssClass generates a valid CSS name? You could throw just any crap at it and it will accept it :-) It's your responsibility not to throw crap at it. AFAIK there's no built-in method for this. Commented Jan 25, 2012 at 23:13
  • You want a helper function to generate a CSS class (e.g. .test { color: Red }), or you just want a way to assign a class name (e.g. test) to a DOM element in your code (code-behind or view)? I'm not sure I totally understand what you want. Commented Jan 25, 2012 at 23:14
  • @Darin Dimitrov maybe I was thinking of the ID generation. I think it swaps out dots so I thought class names were converted to be valid. Guess not! :) Commented Jan 25, 2012 at 23:20

3 Answers 3

3
string className = Regex.Replace(myInput, @"[^a-zA-Z_\-]+", "_");

I know this pattern is overly zealous and replaces characters it shouldn't, like numbers, but it will give you a one-way function for generating valid css class names.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I guess I was overly optimistic thinking it was inbuilt.
Just keep in mind that you cannot guarantee, with this method, that two different inputs always generate different outcome. Like "some class" and "some,class" both give "some_class"
Yeah I appreciate that. Be more than good enough for my requirement. Just didn't want to go adding code if I was missing an obvious in built function.
1

Here's @atornblad solution as an extension method

    public static string ToValidClassName(this string srcString)
    {
        return Regex.Replace(srcString, @"[^a-zA-Z_\-]+", "_");
    }

Makes it 'feel' built in :-)

Comments

0

There is also XmlConvert.EncodeLocalName, which is not pretty, but it is reversible. Xml name and css class have similar naming constrains.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.