写一个Foreach帮助类,在razor中使用

Razor循环改进
本文介绍了一个针对Razor视图引擎的扩展方法,该方法能够简化foreach循环中的索引追踪过程。通过使用此方法,开发者可以在迭代集合的同时轻松获取当前项的索引。

原文发布时间为: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.

转载于:https://www.cnblogs.com/handboy/p/7164020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值