SwissCoder
SwissCoder

Reputation: 2570

How to alternate row style without javascript for DisplayFor/EditorFor bound to a list of model

How can I pass the index of the current element to the View for DisplayFor/EditorFor so that I can decide if the row should show the alternate style or not?

My main view looks like this:

<table>
@Html.EditorFor(model => model.MyListOfItems)
</table>

The view used for the EditorFor looks like:

@Html.HiddenFor(model => model.IdOfTheItem)
<tr class="shouldBeChangedDependingOnRowEvenOrNot">
<td>@Html.CheckBoxFor(model => model.MarkForBatchEdit)</td>
<td>@Html.DisplayFor(model => model.NameOfThisItem)</td>
<td>@Html.DisplayFor(model => model.StateOfThisItem)</td>
</tr>

Well I am aware of this similar question and the suggested solution: alternating row color MVC

But I can't apply them to this case.

Any suggestions?

Upvotes: 0

Views: 537

Answers (1)

Garett
Garett

Reputation: 16828

The EditorFor is overloaded to take an additionalViewData parameter, so you could pass the index in the ViewData, which is a collection of key/value pairs.

@Html.EditorFor( model => model.MyListOfItems , new { CurrentIndex = SomeNumber } )

In your view you would get the value using ViewData["CurrentIndex"].

Also, instead of passing the element index, why not do the calculation in your controller and pass whether you have an even or odd row in your ViewData.

bool isEvenRow = ((CurrentElementIndex % 2) == 0);
ViewData["isEvenRow"] = isEvenRow;

Then you will just toggle your CSS in the view based on whether the value is true or false.

Upvotes: 1

Related Questions