Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor: Render does not work inside code block

Tags:

c#

asp.net

razor

This seems very strange to me, if I do

@RenderSection("scripts", required: false)

then it works perfectly fine, but if I do

@{
    RenderSection("scripts", required: false);
}

then the scripts section will not get rendered and I would get "The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "scripts"." error

Any idea why RenderSection/Script.Render cannot be inside a code block?

Edit: I have tried to put a break point inside the code block and the break point is getting hit when the page loads, and the RenderSection method executes without any exception

like image 541
Steve Avatar asked Oct 02 '22 03:10

Steve


1 Answers

RenderSection does not write anything. Instead this methods returns an HelperResult which implements IHtmlString and can be render to the page by using its WriteTo method.

@{
    HelperResult renderSection = RenderSection("scripts", required: false);
    renderSection.WriteTo(Output);
}

When using @RenderSection it automatically render it to the page

like image 108
meziantou Avatar answered Oct 03 '22 22:10

meziantou