While Microsoft has created some automagic rendering of html attributes in razor MVC4, it took me quite some time to find out how to render a second css class on an element, based on a conditional razor expression. I would like to share it with you.
Based on a model property @Model.Details, I want to show or hide a list item. If there are details, a div should be shown, otherwise, it should be hidden. Using jQuery, all I need to do is add a class show or hide, respectively. For other purposes, I also want to add another class, "details". So, my mark-up should be:
<div class="details show">[Details]</div>
or <div class="details hide">[Details]</div>
Below, I show some failed attempts (resulting mark-up assuming there are no details).
This: <div @(@Model.Details.Count > 0 ? "class=details show" : "class=details hide")>
,
will render this: <div class="details" hide="">
.
This: <div @(@Model.Details.Count > 0 ? "class=\"details show\"" : "class=\"details hide\"")>
.
will render this: <div class=""details" hide"="">
.
This: <div @(@Model.Details.Count > 0 ? "class='details show'" : "class='details hide'")>
will render this: <div class="'details" hide'="">
.
None of these are correct mark-up.