Miguel Angelo
Miguel Angelo

Reputation: 24202

Is it possible to pass a Razor construct to a helper method, using Razor's @: operator?

I am trying to pass some Html constructed by using razor's @: operator to a helper method, but I can not figure out how to do this. The compiler states that the Razor expression is a lambda expression, but it does not say, what is this lambda expression like... no clues at all!

If I try to do this:

        @(MyClass.MyMethod(new
            {
                Html = @:<div></div>
            }
        ))

The error is as follows: Cannot assign lambda expression to anonymous type property

If I try this instead, then it states it as being a lambda again:

        @(MyClass.MyMethod(
            @:<div></div>
        ))

If the MyMethod receives a string: i.e. public string MyMethod(string razorConstructedString) , then the compiler says: Cannot convert lambda expression to type 'string' because it is not a delegate type.

The question is: what type should I declare MyMethod, so that it can receive the razor constructed parameter?

Thanks!

Upvotes: 5

Views: 1579

Answers (1)

SLaks
SLaks

Reputation: 887529

This is called an inline helper.
It's a Func<AnyType, HelperResult>.

You can call this delegate with a parameter, and the parameter will be accessible in the helper, named item.

Upvotes: 9

Related Questions