2

I have a view that has a list and I want to add a class to a specific list item depending on a variable in the view model.

<ul>
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
</ul>

The variable could be anything. Currently it is an integer. Below is what I have now, but I don't think this is the cleanest way to do this.

string[] listClasses = new string[3];
int? selectedListElement= (int?)ViewData["SelectedListElement"];
if(tabNumber.HasValue)
{
    tabClasses[tabNumber.Value] = "selected";
}
<li class="@listClasses[0]">List Item 1</li>
<li class="@listClasses[1]">List Item 2</li>
<li class="@listClasses[2]">List Item 3</li>

1 Answer 1

3

Why not put the class name into your view model and use conditional attributes

Conditional HTML Attributes using Razor MVC3

Sign up to request clarification or add additional context in comments.

2 Comments

So you are saying add 3 variables to my view model and set them to either null or "selected", then in the view do <li class="@listItem1Class">List Item 1</li>?
This is what I ended up doing. Thanks. It removed any logic in the view. Then on the viewModel I just set ViewData["list" + selected + "class"] = "selected" Then in the view I set each list to have a class attribute class="@ViewData["list1class"]", etc. If the viewdata is null conditional attributes save me. Thanks

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.