0

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

<footer [email protected](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?

4
  • Tip: Proper helper methods are extension methods with (this HtmlHelper<T> html, ... as the first parameter. Commented Apr 18, 2018 at 17:54
  • I can't reproduce your behavior locally. What version of ASP.NET are you using? And are you targeting the .NET Framework or .NET Core? Commented Apr 18, 2018 at 17:56
  • Is the method TruthyValueSelector being invoked? Put a debug point to validate if the method is called. Commented Apr 18, 2018 at 17:57
  • 1
    You don't need to use interpolated strings either - just put return firstParameter; or return secondParameter;. Commented Apr 18, 2018 at 17:58

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

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.