Splitting code and markup into different files when creating a Blazor component

 
 
  • Gérald Barré

Their are multiple ways to create a Blazor component, but the most common one is to create a .razor file. A razor file can contains a mix of Razor markup, C#, and HTML.

Razor
<p>@username</p>

@code {
    string username;

    protected override void OnInitialized() => username = "meziantou";
}

Some components may require lots of HTML and C# code. This means the file could be longer and harder to maintain. Also, Visual Studio is not perfect when editing .razor files compared to .cs files. Note that this is something Microsoft is working on. So, in some cases it could be better to split the markup and C# code into different files. This is similar to code-behind in WinForms or WPF.

When you compile a project that contains a .razor file, the .razor files are first compiled to C#. Each razor file is converted to a partial class where the razor markup is used to create the BuildRenderTree method and the @code section is copied as-is. You can see the generated files in the obj folder if you are curious.

Thanks to this compilation step, this is possible to move the @code section into a classic C# file as long as you use a partial class with the same name and namespace as the one generated by the razor file.

  1. Create a file with the same name as the component

  2. Create a partial class with the same name as the component, and move the code from the razor file into the class

    C#
    namespace BlazorDemo.Pages
    {
        public partial class CurrentUser
        {
            string username;
    
            protected override void OnInitialized() => username = "meziantou";
        }
    }

Note that you don't need to move all the code from the @code section to the .cs file. You can keep some code into the .razor file and some into the .cs file.

#Configuring file nesting

By default, Visual Studio shows the file at the same level in the solution explorer.

  • Solution 1: Rename the file from Component.cs to Component.razor.cs

  • Solution 2: Configure Visual Studio to nest files as you want:

    Set the following content to put the .cs files under the .razor files:

    JSON
    {
      "help": "https://go.microsoft.com/fwlink/?linkid=866610",
      "dependentFileProviders": {
        "add": {
          "extensionToExtension": {
            "add": {
              ".cs": [
                ".razor"
              ]
            }
          }
        }
      }
    }

    Finally, enable the custom settings:

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub