HtmlHelper in ASP.NET MVC3 that uses Action <T> as a template: Razor syntax?
Let me preface this by saying that there may be a better way to do this, and Razor highlights the way. In any case, I have an HTML helper that acts like a sort repeater, but after an arbitrary number of repetitions, it inserts an alternative pattern. The most obvious use? Tables that start a new row after x-cells. The helper is as follows:
public static void SeriesSplitter<T>(this System.Web.Mvc.HtmlHelper htmlHelper, IEnumerable<T> items, int itemsBeforeSplit, Action<T> template, Action seriesSplitter)
{
if (items == null)
return;
var i = 0;
foreach (var item in items)
{
if (i != 0 && i % itemsBeforeSplit == 0)
seriesSplitter();
template(item);
i++;
}
}
And in the Webforms view, the usage is as follows:
<table>
<tr>
<% Html.SeriesSplitter(Model.Photos, 4, photo => { %>
<td><img src="<%=ResolveUrl("~/Thumbnail.ashx?id=" + photo.ID)%>" alt="<%=Html.Encode(photo.Title)%>" /></td>
<% }, () => { %></tr><tr><% }); %>
</tr>
</table>
, , , ( ). , Razor. Razor .
?
+3
2
Func<object, HelperResult> ( , ):
public static void SeriesSplitter<T>(this System.Web.Mvc.HtmlHelper htmlHelper,
IEnumerable<T> items,
int itemsBeforeSplit,
Func<object, HelperResult> template,
Func<object, HelperResult> seriesSplitter) {
//pretty much same code here as before
}
@Html.SeriesSplitter(Model.Items, 3, @<td>item.Id</td>, @:</td><td>
)
, - , Razor , @:</td><td>
+1