Generating multi CSS class names with Razor in ASP.Net

时间:2018-04-18 17:52:54

标签: c# asp.net razor razor-pages

I need to generate multi CSS class names in a view using Razor, however Razor treats white space a bit tricky

<footer class=@HtmlHelpers.TruthyValueSelector(false,"footer","footer footer--no--border">

</footer>

My helper method:

public static string TruthyValueSelector(bool condition, string firstParameter, string secondParameter)
        {
            if (condition)
                return $"{firstParameter}";
            return $"{secondParameter}";
        }

when I inspect the element, the footer css class is: class="footer" footer--no--border=""

Of course, this is not going to work. My attempts in handling this situation cleanly with C# and Razor has not been successful. How can I take care of this in Razor?

1 个答案:

答案 0 :(得分:1)

You could just use the ternary operator:

<footer class="@( someBooleanValue ? "footer" : "footer footer--no--border" )">

</footer>

This renders like this on my machine (when someBooleanValue is false):

<footer class="footer footer--no--border">

</footer>