0

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

For the same reason that you cannot write x => "abc"; as a normal statement. There is no way to emit HTML as an embedded statement in Razor; you need to use it as a lambda.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.