开发者

ASP.NET MVC Razor - lambda error

开发者 https://www.devze.com 2023-02-23 16:06 出处:网络
I have an extension method public static HelperResult List<T> (this IEnumerable<T> items, Func<T, HelperResult> template) {

I have an extension method

public static HelperResult List<T> (this IEnumerable<T> items, Func<T, HelperResult> template) {

            return new HelperResult(writer =>{
                foreach (var item in items)
                    template(item).WriteTo(writer);
            });

        }

When I try to use this method like this

  <ol>
     @Model.List(t=> {@<li>@t.Title</li>});
  </ol> 

I get an error "; expected"

But if I do

<ol>
    @Model.List( @<li>@item.Title</li>)
  开发者_开发知识库 </ol>

it's OK. (what is the variable "item"? Where does it define?)

Why does the first example throws an error?


The one solution is to declare razor helper like this

@helper ItemWriter(string item)
{
    <li>@item.Title</li>
}

And then pass this to your extension function

@Model.List(ItemWriter)

I know this code can be made better, but this works. Main idea is to use Razor Helpers


The syntax @<tagname>...</tagname> declares a lambda expression that takes a parameter named item and returns a HelperResult.

You cannot use it as a statement; your first example cannot work.


That's pretty much the reason why I had to create Castle.Blade. It supports @=> p ... as an expression to create a lambda with named args. It also supports nesting these declarations, which razor doesn't.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号