Razor支持lambda表达式吗? [英] Are lambda expressions supported by Razor?

查看:87
本文介绍了Razor支持lambda表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Razor视图引擎是否支持lambda表达式/匿名方法?

我很难在Razor中表达以下内容:

I am having difficulty expressing the following in Razor:

@Model.ToList().ForEach(i =>
    {
        if (i.DealerName != null) 
        {
            <text> 
                @i.DealerName
            </text>
        }
    }

注意:我知道可以用@foreach解决此问题,但对于第三方MVC控件,我需要类似的解决方案.它使用这种机制来设置控件的内容.它适用于MVC .ASPX视图,但无法使其与Razor一起使用.

Note: I know can solve this with @foreach but I need a similar solution for a 3rd party MVC control. It using this mechanism for setting the content of the control. It works fine for MVC .ASPX views but cannot get it to work with Razor.


相当于MVC .ASPX(我想转换为Razor语法的代码):

MVC .ASPX equivalent (the code I would like to convert to Razor syntax):

<% Model.ToList().ForEach(i =>
       {
           if (i.DealerName != null)
           { 
           %> <%=i.DealerName%> <%
           };
       }); 
%>

这是针对ASP.NET MVC3附带的Razor引擎的.

This is for the Razor engine that ships with ASP.NET MVC3.

推荐答案

您可以使用Response.Write(i.DealerName);

结果是一样的,就像将它放在Razor页面中一样-它会在渲染页面时执行.坦率地说-我很确定这是它将被编译成的内容.

The result is the same, as if you drop this in a Razor page - it will execute while rendering page.. And frankly - I'm pretty sure this is what it will be compiled into anyway.

此外,由于ForEach()返回void,因此您必须将其作为代码块放置在页面中. 因此您的代码应如下所示:

Also, since ForEach() returns void, you'd have to drop it in the page as a code block. So your code would look something like this:

@{
    Model.ToList().ForEach(i =>
    {
        if (i.DealerName != null) 
        {
            Response.Write(i.DealerName);
        }
    });
}

UPD::如果您使用更严肃的格式,则可以使用这个不错的小技巧:
(不幸的是,这里的代码着色不会使该代码段有任何用处,但是如果将其放到Visual Studio中,您肯定会明白我的意思.注意:这仅适用于Razor页面,而不适用于代码文件:))

UPD: If you have more serious formatting, you can resort to this nice little trick:
(unfortunately the code colouring here will not give this snippet any credit, but you'll definitely see what I mean if you drop this in visual studio. Note: this will only work in Razor pages, not code files :) )

@{
    Model.ToList().ForEach(i =>
    {
        if (i.DealerName != null) 
        {
            Response.Write(((Func<dynamic, object>)(
                @<text>
                    <b>Hello Dealer named: @item.DealerName
                    Multiline support is <em>Beautiful!</em>
                </text>)).Invoke(i));
        }
    });
}

有希望的希望:)

这篇关于Razor支持lambda表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆