Razor 支持 lambda 表达式吗?
Razor 视图引擎是否支持 lambda 表达式/匿名方法?
我在 Razor 中表达以下内容时遇到困难:
@Model.ToList().ForEach(i =>
{
if (i.DealerName != null)
{
<text>
@i.DealerName
</text>
}
}
注意: 我知道可以使用 @foreach 解决此问题
但我需要一个类似的第三方 MVC 控件解决方案。它使用这种机制来设置控件的内容。它适用于 MVC .ASPX 视图,但无法使其与 Razor 一起使用。
MVC .ASPX 等效项(我想要转换为 Razor 语法的代码):
<% Model.ToList().ForEach(i =>
{
if (i.DealerName != null)
{
%> <%=i.DealerName%> <%
};
});
%>
这适用于 ASP.NET MVC3 附带的 Razor 引擎。
Are lambda expressions/anonymous methods supported in the Razor view engine?
I am having difficulty expressing the following in Razor:
@Model.ToList().ForEach(i =>
{
if (i.DealerName != null)
{
<text>
@i.DealerName
</text>
}
}
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 equivalent (the code I would like to convert to Razor syntax):
<% Model.ToList().ForEach(i =>
{
if (i.DealerName != null)
{
%> <%=i.DealerName%> <%
};
});
%>
This is for the Razor engine that ships with ASP.NET MVC3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Response.Write(i.DealerName); 代替
@i.DealerName
块,结果是相同的,如下所示如果你把它放在 Razor 页面中 - 它将在渲染页面时执行。坦率地说 - 我很确定这就是它将被编译成的内容。
另外,由于
ForEach()
返回 void,因此您必须将其作为代码块放入页面中。所以你的代码看起来像这样:
UPD:如果你有更严格的格式,你可以诉诸这个漂亮的小技巧:
(不幸的是,这里的代码着色不会给这个片段任何信用,但如果你把它放到 Visual Studio 中,你肯定会明白我的意思。注意:这仅适用于 Razor 页面,不适用于代码文件:))
希望这使得感觉 :)
Instead of your
<text>@i.DealerName</text>
block you could use aResponse.Write(i.DealerName);
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.
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:
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 :) )
Hope that makes sense :)
或者,您可以创建一个 lambda 函数,并为 Razor 代码主体中的每个项目调用该函数(这个想法来自 Andy 在 this帖子):
Alternatively, you can create a lambda function, and call that for each item in the body of your Razor code (the idea came from Andy in this post):
是的,他们受到支持。但是,Razor 有一些奇怪的转义规则,额外的大括号有时会导致它阻塞,包括扩展 lambda 表达式中的大括号。
您可以稍微简化 @Artioms 答案,以使用 where 和可选的 select 子句删除那些额外的大括号
Yay
也可以成为
函数样式!
Yes, they are supported. BUT, Razor has some weird escaping rules and extra braces will cause it to choke sometimes, including those in extended lambda expressions.
You can simplify the @Artioms answer a bit to remove those extra braces with a where and optionally a select clause
becomes
Could also become
Yay functional styles!