我正在做一个组件来格式化一个列表,它是一个扩展,我写了下面的代码,但是,在执行时,它给了我错误:
Cannot convert lambda expression to type 'System.Web.WebPages.HelperResult' because it is not a delegate type
这是扩展:
public static MvcHtmlString FormatMyList<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, IEnumerable<TValue> list,
Expression<Func<TValue, System.Web.WebPages.HelperResult>> formatExp = null)
{
foreach (var item in list)
{
var itemFormated = formatExp.Compile().Invoke(item).ToString();
}
return new MvcHtmlString("");
}
查看调用:
var test = Html.FormatMyList<ModelType, ListType>(list, formatExp:
x =>
@<text>
This is format of @x.Cambio to test @x.Fala
</text>);
我已经尝试将 HelperResult 更改为 dynamic,但也没有成功。
我不想只使用 Func<object, HelperResult>
正如 StackOverFlow 中一些帖子所建议的那样,因为 <text></text>
中会有项目, 需要强类型化为 ListType 的一项。
在我的 View 中格式可能不同,所以我不能使用 ListType 的模板。
有没有办法做到这一点,即使不使用表达式?
谢谢
最佳答案
我做到了,而不是使用表达式 Expression<Func<TValue, System.Web.WebPages.HelperResult>>
, 我只用了一个 Func:
Func<TValue, System.Web.WebPages.HelperResult>
查看:
var test = Html.FormatMyList<ModelType, ListType>(list, format:
@<text>
This is format of @item.Cambio to test @item.Fala
</text>);
我使用“item”键访问 LisType 属性。
使用表达式的唯一原因是访问强类型属性,因为我可以使用“item”键,我不再需要表达式了。
它对我有用,谢谢。
关于c# - HelperResult 的表达式以格式化列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667029/