c# - HelperResult 的表达式以格式化列表中的项目

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

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

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/

相关文章:

c# - 事务中止时如何获取错误详细信息

c# - 如何创建一个临时表并在与 Entity Framework 的相同连接中使用它?

javascript - amCharts 的 JS 图表折线图中的随机曲线

c# - ASP.NET Web API 上 HttpActionContext.RequestContentKeyValueModel 的替代方案

c# - 如何在不查看/将实体更改为字符的情况下使用 XElement.Parse 解析 XML?

html - 如何在 Release 模式下自动删除 HTML 注释?

asp.net-mvc - 您如何在 MVC .net 中测试 cookie?

c# - ASP.NET MVC 以分发包的形式部署

c#-4.0 - ASP.NET MVC 4 cookie 消失

css - MVC razor 获取 div 宽度并检查条件