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>
}