如何在不使用javascript的情况下将行样式替换为DisplayFor / EditorFor绑定到模型列表

时间:2012-10-29 05:07:08

标签: asp.net-mvc-3

如何将当前元素的索引传递给View for DisplayFor / EditorFor,以便我可以决定该行是否应该显示替代样式?

我的主要观点如下:

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

用于EditorFor的视图如下所示:

@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>

我知道这个类似的问题和建议的解决方案:alternating row color MVC

但我不能将它们应用于这种情况。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

重载EditorFor以获取additionalViewData参数,因此您可以传递ViewData中的索引,这是键/值对的集合。

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

在您的视图中,您将使用ViewData["CurrentIndex"]获得该值。

此外,为什么不在控制器中进行计算,而不是传递元素索引,并传递ViewData中是否有偶数行或奇数行。

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

然后,您只需根据值是true还是false来切换视图中的CSS。

相关问题