Search code examples
blazorblazor-server-sideblazor-webassembly

Can the code block be used before the HTML in blazor?


Blazor templates seem to follow this order to write components and pages:

@page "/users"

<h1>List of users</h1>

@code{
   // your code here
}

I am wondering, if there may be any known inconveniences on using the code block before the HTML. Therefore:

@page "/users"

@code{
   // your code here
}

<h1>List of users</h1>

Solution

  • That is perfectly alright. Not being 'standard' is the only inconvenience.

    You can have more than 1 @code block so you can put one before and after and even in the middle of the markup.

    The .razor file is processed like:

    • a partial class is generated based on the filename
    • code from @code blocks is copied inside that class (in order)
    • code outside any @code block is collected into the BuildRenderTree() method.