Expression of HelperResult to format item from a list

假装没事ソ 提交于 2019-12-23 11:52:22

问题


I'm doing a component to format a list, it is an Extension, I wrote the following code, but, when in execution time, it gives me the error:

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

View calling:

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 change from HelperResult to dynamic, but didn't work too.

I don't want to use only Func<object, HelperResult> as suggested in some posts in StackOverFlow, because, there will be items inside the <text></text>, that needs to be strongly typed as an item of ListType.

The format can be different in my views, so I can't use a template to ListType.

Is there a way to do that, even that not using the expression?

Thanks


回答1:


I did it, instead of use an expression Expression<Func<TValue, System.Web.WebPages.HelperResult>>, I used only a 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 the LisType properties.

The unique reason to use an expression, was to access the properties strongly typed, as I can use the "item" key, I don't need a Expression anymore.

It works to me, thanks.



来源:https://stackoverflow.com/questions/31667029/expression-of-helperresult-to-format-item-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!