【问题标题】:Expression of HelperResult to format item from a listHelperResult 的表达式以格式化列表中的项目
【发布时间】:2015-07-28 21:25:54
【问题描述】:

我正在做一个组件来格式化列表,它是一个扩展,我写了以下代码,但是,在执行时,它给了我错误:

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

查看调用:

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

我已经尝试从 HelperResult 更改为 dynamic,但也没有用。

我不想像 StackOverFlow 的一些帖子中建议的那样只使用Func&lt;object, HelperResult&gt;,因为&lt;text&gt;&lt;/text&gt; 内会有项目需要强类型为 ListType 的项目。

在我的视图中格式可能不同,所以我不能使用模板来 ListType。

有没有办法做到这一点,即使不使用表达式?

谢谢

【问题讨论】:

  • 您将FormatMyList() 标记为扩展方法,但您没有在任何对象上调用它。相反,您将其用作静态方法,这意味着您缺少其中一个参数。
  • 你传递 formatExp 不是 Expression 而是 Func。
  • 它是HtmlHelper的一个扩展,在这段代码中可以看到:Htm.FormatMyList。在这种情况下,Html 是一个 HtmlHelper。
  • 将formatExp的签名更改为Func&lt;TValue, System.Web.WebPages.HelperResult&gt;

标签: c# asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

我做到了,而不是使用表达式 Expression&lt;Func&lt;TValue, System.Web.WebPages.HelperResult&gt;&gt;,我只使用了一个 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”键,我不再需要表达式。

它对我有用,谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 2022-06-10
    • 1970-01-01
    • 2016-05-13
    • 2011-04-02
    • 2023-03-24
    • 2015-04-03
    • 2013-01-20
    相关资源
    最近更新 更多