Html expressions like lambdas in a razor - what is allowed, where is this documented

I just stumbled upon the most amazing feature in Razor that I completely missed.

You can define

public delegate IHtmlString RazorBlock(Object unknown);

and some function

public static IHtmlString Foo(RazorBlock block) => block(null);

and then name it using the Razor snippet:

@(
    Helper.Foo(@<div>some text</div>)
)

Internal html is what the method gets Foo.

I always thought that Razor nesting in lambda is not supported. But this. The razor goes a lot further than I thought.

My only question is:

I found this function by looking at samples from DevExtreme ASP.NET MVC wrappers, and from here comes the definition RazorBlock.

I do not know why the parameter is unknownnecessary (though) and how it can be obtained from the Razor fragment.

+4
1

, ( ) Razor.

, Razor ( % windir%\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET).

, :

@functions{ 
    public delegate IHtmlString RazorBlock(Object unknown);

    static object Helper(RazorBlock block) {
        return null;
    }
}

@Helper(@<text>
    multi-line
    text
</text>)

:

public class _Page_Views_Home_Index_cshtml : System.Web.Mvc.WebViewPage<dynamic> {
    public delegate IHtmlString RazorBlock(Object unknown);

    static object Helper(RazorBlock block) {
        return null;
    }

    // . . .

    public override void Execute() {
        // . . .

        Write(Helper(item => new System.Web.WebPages.HelperResult(__razor_template_writer => {            
            BeginContext(__razor_template_writer, "~/Views/Home/Index.cshtml", 174, 28, true);
            WriteLiteralTo(__razor_template_writer, "\r\n    multi-line\r\n    text\r\n");
            EndContext(__razor_template_writer, "~/Views/Home/Index.cshtml", 174, 28, true);
        })));

        // . . .
    }
}

. , @<text></text> item => HelperResult lambdas. object => IHtmlString - , .

+1

Source: https://habr.com/ru/post/1648638/


All Articles