Чтобы избавиться от неловкости if / else, вы можете использовать блок using:
@{
var count = 0;
foreach (var item in Model)
{
using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
{
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.Truncate(item.Details, 75)
</td>
<td>
<img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()"
alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
@Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
</td>
}
}
}
Повторно используемый элемент, облегчающий добавление атрибутов:
//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
private object _htmlAttributes;
private TagBuilder _tr;
public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
{
_htmlAttributes = htmlAttributes;
}
public override void BeginBlock()
{
_tr = new TagBuilder("tr");
_tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
}
protected override void EndBlock()
{
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
}
}
Вспомогательный метод для уточнения синтаксиса бритвы:
public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
var tableRow = new TableRow(self, htmlAttributes);
tableRow.BeginBlock();
return tableRow;
}