HelperResult expression to format an item from a list

I am making a component for formatting a list, this is an extension, I wrote the following code, but when it gives me an error at runtime:

Cannot convert lambda expression to type 'System.Web.WebPages.HelperResult' because it is not a delegate type

This is the extension:

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(""); } 

Call View:

 var test = Html.FormatMyList<ModelType, ListType>(list, formatExp: x => @<text> This is format of @x.Cambio to test @x.Fala </text>); 

I already tried to switch from HelperResult to dynamic, but did not work either.

I do not want to use only Func<object, HelperResult> , as suggested in some posts in StackOverFlow, because there will be elements inside <text></text> that must be strongly typed as ListType elements.

The format may be different in my views, so I can not use the template for ListType.

Is there any way to do this, even if not using an expression?

thanks

+5
source share
1 answer

I did this, instead of using the Expression<Func<TValue, System.Web.WebPages.HelperResult>> expression Expression<Func<TValue, System.Web.WebPages.HelperResult>> , I used only Func:

 Func<TValue, System.Web.WebPages.HelperResult> 

View:

 var test = Html.FormatMyList<ModelType, ListType>(list, format: @<text> This is format of @item.Cambio to test @item.Fala </text>); 

I used the "item" key to access LisType properties.

The only reason to use the expression was to access strongly typed properties, since I can use the "item" key, I no longer need an expression.

He works with me, thanks.

0
source

All Articles