写一个Foreach帮助类,在razor中使用
原文发布时间为:2011-05-05 —— 来源于本人的百度文章 [由搬家工具导入]
A Better Razor Foreach Loop(razor delegate extension)
http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx
There are many situations where I want to quickly iterate through a bunch of items in a view, and I prefer using the foreach statement. But sometimes, I need to also know the current index. So I wrote an extension method to IEnumerable<T> that accepts Razor syntax as an argument and calls that template for each item in the enumeration.
publicstaticclassHaackHelpers {publicstaticHelperResult Each<TItem>(
thisIEnumerable<TItem> items,
Func<IndexedItem<TItem>,
HelperResult> template) {
returnnewHelperResult(writer => {
intindex = 0;
foreach(var iteminitems) {
var result = template(newIndexedItem<TItem>(index++, item));
result.WriteTo(writer);
}
});
}
}
This method calls the template for each item in the enumeration, but instead of passing in the item itself, we wrap it in a new class, IndexedItem<T>.
publicclassIndexedItem<TModel> {publicIndexedItem(intindex, TModel item) {
Index = index;
Item = item;
}
publicintIndex { get;privateset; }
publicTModel Item { get;privateset; }
}
And here’s an example of its usage within a view. Notice that we pass in Razor markup as an argument to the method which gets called for each item. We have access to the direct item and the current index.
@model IEnumerable<Question><ol>
@Model.Each(@<li>Item@item.Index of@(Model.Count() - 1):@item.Item.Title</li>)
</ol>
If you want to try it out, I put the code in a package in my personal NuGet feed for my code samples. Just connect NuGet to http://nuget.haacked.com/nuget/ and Install-Package RazorForEach. The package installs this code as source files in App_Code.