MVC4 Conditional HTML Attributes

MVC4 made one simple and yet awesome improvement to View rendering that I don’t think many people are aware of.

Have you ever had to conditionally add an attribute to an HTML element in your MVC View based on the presence of a variable? The typical use case is applying a CSS class to a div. Most of the time that code looks something like this:

<div @(myClass == null ? "" : "class=\"" + myClass + "\"")></div>

What a pain – not only to write but to read… This destroys the View’s readability and clutters the HTML up big time!

In MVC4, this process is much simpler. Just do this instead:

<div class="@myClass"></div>

That’s all you need. If myClass == null it will ignore the class attribute and render without the class:


If myClass != null it will apply the class to the div:

<div class="test"></div>

This should work with other HTML element attributes also, though I haven’t tested them all myself. What a great little improvement!

See also

comments powered by Disqus