在 Razor 中使用 ForEach 扩展 [英] Use ForEach extension in Razor

查看:57
本文介绍了在 Razor 中使用 ForEach 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 IEnumerable 扩展来遍历集合并获取其索引:

I am using an IEnumerable extension to loop through a collection and also get its index:

@Model.ForEach((card, i) => {
  @<li class="c@(i)">@card.Text</li>;
})

ForEach 扩展如下:

The ForEach extension is the following:

public static void ForEach<T>(this IEnumerable<T> source, Action<T, Int32> action) {

  Int32 i = 0;
  foreach (T item in source) {
    action(item, i);
    i++;
  }

} // ForEach

但是当我尝试编译它时,我收到以下错误消息:

But when I try to compile it I get the following error message:

参数 1:无法从 'void' 转换为'System.Web.WebPages.HelperResult'

Argument 1: cannot convert from 'void' to 'System.Web.WebPages.HelperResult'

我该如何解决这个问题?我需要一个新的扩展程序吗?

How can I solve this? Do I need a new extension?

推荐答案

您的问题是 Razor 期望您的 ForEach 方法返回一个值,例如 MvcHtmlString.

Your problem is that Razor expects your ForEach method to return a value, such as MvcHtmlString.

此外,您不能简单地期望 Razor 将您的 foreach 子句的主体转换为与您的 Action 委托一起使用.有一种方法可以让它发挥作用,但它并不那么漂亮.如果您想使用标准的 razor 语法,我建议您使用 @for(...) 子句,正如 James 建议的那样.

Also, you cannot simply expect Razor to translate the body of your foreach clause to work with your Action delegate. There is a way to get this to work, but it's not as pretty. I'd suggest using the @for(...) clause as James suggested if you want to use the standard razor syntax.

但是,这里有一个可行的实现:

However, here's an implementation that does work:

public static MvcHtmlString ForEach<T>(this IEnumerable<T> source, Func<T, Int32, string> selector)
{
    return new MvcHtmlString(String.Join("\n", source.Select(selector)));
}

用法:

@Model.ForEach((card, i) =>
{
    return "<li class=c" + i + ">" + card.Text + "</li>";
})

这篇关于在 Razor 中使用 ForEach 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆