Razor支持lambda表达式吗?

编程入门 行业动态 更新时间:2024-10-20 13:37:22
本文介绍了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表达式吗?

本文发布于:2023-11-08 07:38:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   Razor   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!