1

What would be the best way to add/remove a css class to a div from the controller?

I have a div in a razor view like so (simplified)

<div id="divToToggle" class="hidden">
     //content
</div>

In my controller, depending if there is content or not, I want to add or review that class="hidden".

if (model.name.HasAValue())
{
    model.company = Method();
    //Toggle div to visible here.
}

I have thought about making a new property in the model and setting that value and then in the razor view doing like class="@Model.CssName" However, I have numerous tabs to deal with and don't want to clutter the model up with another set of css properties. What would be the most efficient way to do this?

2 Answers 2

4

In view you can do:

<div id="divToToggle" class=@(model.name.HasAValue()?"hidden":"visible")> 
 //content 
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

When I try that I get that the is no extension method HasValue(). Do you mean HasAValue() and then include @using TrafficBlazer.Mvc.Application.HtmlHelpers.Extensions; in viewstart?
0

You can also add class, if you have array of class and you want to append in foreach loop

<div class="panel @arrayClass[count1] panel-stat">
</div>

If you have class returning from model

<div class="panel @model.class panel-stat">
<div>

Or you can also use if condition or ternary operator as per your requirement you can do what you want to achieve.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.