I’m trying to dynamically add a class to a div in an MVC View; in this case error. I find myself creating a Razor If-Else block which means my view has lots of duplicated code. I have tried a few differant Razor scenario’s but can’t find a reasonable way to conditionally append new classes. Can anyone suggest an approach that avoids duplicating code and keeps View decisions in the View.
@if (ViewData.ModelState["Title"] != null && ViewData.ModelState["Title"].Errors.Any())
{
<div class="select error">
@Html.DropDownListWithTooltipFor(m => m.Title, Model.Titles, new { required = string.Empty, @class = "sel" })
</div>
}
else
{
<div class="select">
@Html.DropDownListWithTooltipFor(m => m.Title, Model.Titles, new { required = string.Empty, @class = "sel" })
</div>
}
Try this:
Razor will add the quotes for you (class = “select error”). This should work in MVC3.
Also, take a look at: Conditional HTML Attributes using Razor MVC3 and MVC3 – Conditionally add id element with Razor (actually pretty much duplicates)
Note the answer of Erik Porter: If you can do it with MVC4, then there’s a more elegant way: