Razor icon indicating copy to clipboard operation
Razor copied to clipboard

Templated Razor Delegates within a @section = '__razor_template_writer': a parameter or local variable cannot have the same name as a method type parameter

Open nikoszs opened this issue 10 years ago • 2 comments

I'm having problems creating templated razor delegates within a section of a page.

_Layout.chtml

@RenderSection("test", false)

_SubLayout.cshtml

@section test {
    @ { Func<dynamic, object> f = @<span>@item</span>; }
}

Which gives me this error:

CS0412 '__razor_template_writer': a parameter or local variable cannot have the same name as a method type parameter

So I went to look at what gets generated, and this is it

Func<dynamic, Microsoft.AspNet.Mvc.Razor.HelperResult> e = 
    item => new Microsoft.AspNet.Mvc.Razor.HelperResult(async (__razor_template_writer) =>
    {
        BeginContext(2881, 6, true);
        WriteLiteralTo(__razor_template_writer, "<span>");
        EndContext();
        BeginContext(2888, 4, false);
        WriteTo(__razor_template_writer, item);
        EndContext();
        BeginContext(2893, 7, true);
        WriteLiteralTo(__razor_template_writer, "</span>");
        EndContext();
    });

So the error makes sense, in the section there's already a method parameter called __razor_template_writer when a section is created, and now by creating a templated razor delegate, it tried to create another '__razor_template_write' parameter, hence the error.

I then copied the above code to my view just changed the method parameter name from __razor_template_writer to __test in the above function and called @e("this is a test"). It works.

I tested the initial problem code in MVC5 and works fine, so my question is, is this a bug?

It smells like one. And also, is there a way around it?

nikoszs avatar Jan 21 '16 19:01 nikoszs

@alzdrak I suspect __razor_template_writer will be used as a lambda parameter for both the section (@section test { ... }) and the template (@<span>@item</span>). Further the two lambdas should nest in the generated code. Could you check the @section code and its relation to the block you pasted above to confirm? Uploading the whole file or placing it in a gist may help as well.

Anything that avoids templates w/in a section (such as your @e("this is a test")) should work around the issue.

dougbu avatar Jan 21 '16 20:01 dougbu

6bad1bba5b8ef1429a634ddc7c4d2907e6719e73

NTaylorMullen avatar Feb 11 '16 20:02 NTaylorMullen