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>
dove
  • 20,469
  • 14
  • 82
  • 108
Michael
  • 3,222
  • 2
  • 21
  • 22

1 Answers1

3

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

Conditional HTML Attributes using Razor MVC3

Community
  • 1
  • 1
dove
  • 20,469
  • 14
  • 82
  • 108
  • So you are saying add 3 variables to my view model and set them to either null or "selected", then in the view do
  • List Item 1
  • ? – Michael Oct 25 '12 at 18:10
  • 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 – Michael Oct 25 '12 at 18:39