Including functions in _ViewStart.cshtml I've got the following code in my _ViewStart.cshtml file:

@using System.Text;
@{
    string controllerName = (string)ViewContext.RouteData.Values["controller"];
    ViewContext.Controller.ViewBag.BodyCssClass = ConvertControllerNameToCssClass(controllerName);
}

@functions {
    private static string ConvertControllerNameToCssClass(string text)
    {
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }

        StringBuilder sb = new StringBuilder();
        sb.Append(text[0]);
        for (int i = 1; i &lt; text.Length; i++)
        {
            if (char.IsUpper(text[i]) &amp;&amp; text[i - 1] != '-')
            {
                sb.Append('-');
            }
            sb.Append(text[i]);
        }
        return sb.ToString().ToLower();
    }
}


In my layout the ViewBag.BodyCssClass is used like so:

&lt;body class="@ViewBag.BodyCssClass" itemscope itemtype="https://schema.org/WebPage"&gt;


Allowing me to target a particular page with CSS specific to that controller where required.

The ConvertControllerNameToCssClass function has limited use, in that it is not likely to be used elsewhere and shouldn't be used elsewhere either.

However, it is my understanding that the _ViewStart.cshtml is supposed to be used for adding code that would otherwise be duplicated across all views. Is it acceptable to add functions to the _ViewStart.cshtml?

Does anyone have any thoughts on this or any alternatives to how they would implement something like this?
The ConvertControllerNameToCssClass function has limited use, in that it is not likely to be used elsewhere and shouldn't be used elsewhere either.


It looks like the function converts a PascalCase input text to dash-separated-words format.
This is actually a quite common text transformation to do.
In some frameworks it's called "slugify",
and I would prefer this shorter name instead of the current very long name.
(Another naming idea: ToCssClass)



You seem to have a bug:
you check if the input is null,
but you don't check if it's empty.
If it's empty, then this line will throw an exception:


    sb.Append(text[0]);





Instead of transforming the input character by character,
it would be much simpler to use a regex.
I don't know the syntax in C#,
I hope this Perl/Bash example might help:


$ perl -pe 's/[A-Z]/-\L$&amp;/g; s/^-//' &lt;&lt;&lt; HelloWorldThere
hello-world-there