1

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

1 Answer 1

3

Try this:

 <div @(condition ? "class=select error" : "class = select">
 </div>

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:

<div class="@yourClass" />
Sign up to request clarification or add additional context in comments.

3 Comments

@artur_udod I tried <div @(ViewData.ModelState["Title"] != null && ViewData.ModelState["Title"].Errors.Any() ? "class=select error" : "class=select") > but it resulted in <div class=select error >. This obviously is wrong... I tried to escape quotes but then it renders the encoded version which is also wrong. Any ideas?
Ok, I got it... this sample works. <div class="@((ViewData.ModelState["Title"] != null && ViewData.ModelState["Title"].Errors.Any()) ? "select error" : "select")" >
<div class="@yourClass" /> is not a more elegant way, the CSS just leaked out of the view and into the controller, no bueno

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.