6134548
6134548

Reputation: 95

How can I add a class to an html element through a controller?

I'm busy with an mvc 5 application. I have a list of names from a database which are displayed in html. I filter the names alphabetically using html.actionlink for A, B, C, D ...Z. Through each html.actionlink I pass through each letter as an Id parameter and then in my controller I filter which names are returned using .ToList() by finding .Where() the first letter of my names match the Id parameter.

That is all working well. What I need to do now is that if there are no names which begin with a certain letter then that letter must be grayed out in the view.

How can I add a class to an html element through my controller? I need to make sure that if there are no names with a certain letter then my html link must have css class with color: grey. I don't know which names there will be because the database is populated by an administrator.

Upvotes: 0

Views: 534

Answers (3)

Hussain Rauf
Hussain Rauf

Reputation: 298

You can define your CSS class and apply your class in html helpers. Like this:

.yourClassName
{
 color:grey;
}

Applying your class:

@Html.ActionLink("Name", "{Controller}", null,new { @class ="yourClassName" })

Upvotes: 1

Alex
Alex

Reputation: 422

Not too sure I follow the design flow in your question but I think this code may help you.

@if(model.Names.Where(x => x.StartsWith("L").Count() != 0)
{
     @Html.ActionLink("L", "{Controller}", "{Action}", null, new {} { @class = "{NOT GRAY}"})
}
@else
{
     @Html.ActionLink("L", "{Controller}", "{Action}", null, new {} { @class = "grayed"})
}

Basically, you can write an IF statement in Razor syntax and then check and see if the incoming data is empty by doing a Count and then styling the element differently for each case.

Because I don't know what name you are using for your model, what classes your applying to your not grayed elements, controller names, action names, then you will need to edit to this code to get it to work.

Upvotes: 0

Emmanuel DURIN
Emmanuel DURIN

Reputation: 4913

Using ActionLink function you can pass an anonymous object with entries corresponding to Html attributes.

Look at the parameter of type object, called htmlAttributes in the ActionLink function.

Here is an example (note that class is prefixed with @ because it is a keyword) :

@Html.ActionLink(
       "Portfolio", 
       "Index", 
       "Portfolio", 
       routeValues: null, 
       htmlAttributes: new { @class = "grayed" }
)

Upvotes: 0

Related Questions