Rod*_*ite 5 c# asp.net-mvc razor asp.net-mvc-4
我正在做一个组件来格式化一个列表,它是一个扩展,我写了下面的代码,但是,在执行时,它给了我错误:
无法将lambda表达式转换为类型'System.Web.WebPages.HelperResult',因为它不是委托类型
这是扩展:
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("");
}
Run Code Online (Sandbox Code Playgroud)
查看电话:
var test = Html.FormatMyList<ModelType, ListType>(list, formatExp:
x =>
@<text>
This is format of @x.Cambio to test @x.Fala
</text>);
Run Code Online (Sandbox Code Playgroud)
我已经尝试从HelperResult更改为动态,但也没有工作.
我不想只使用Func<object, HelperResult>StackOverFlow中的某些帖子中的建议,因为,里面会有项目<text></text>,需要强类型化为ListType项目.
我的视图中的格式可能不同,因此我无法将模板用于ListType.
有没有办法做到这一点,即使不使用表达式?
谢谢
我做到了,我没有使用表达式Expression<Func<TValue, System.Web.WebPages.HelperResult>>,而是只使用了 Func:
Func<TValue, System.Web.WebPages.HelperResult>
Run Code Online (Sandbox Code Playgroud)
看法:
var test = Html.FormatMyList<ModelType, ListType>(list, format:
@<text>
This is format of @item.Cambio to test @item.Fala
</text>);
Run Code Online (Sandbox Code Playgroud)
我使用“item”键来访问 LisType 属性。
使用表达式的独特原因是访问强类型的属性,因为我可以使用“item”键,所以我不再需要表达式。
这对我有用,谢谢。
| 归档时间: |
|
| 查看次数: |
449 次 |
| 最近记录: |