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!

One minute to read