Dan Schnau

How To Move Blazor Component Code into a Code Behind

Here’s the steps to getting a Blazor Component’s code out of a @Code block and into it’s own file.

It doesn’t take much to make a one-file blazor component hard to work with since there’s markup and logic in the same file.

Let’s call our example component ExampleComponent.razor.

  1. In the same directory as ExampleComponent.razor, add a file ExampleComponent.razor.cs. Visual Studio should nest it appropriately.
  2. Change the new class name from ExampleComponent to ExampleComponentBase and have that class inherit from Microsoft.AspNetCore.Components.ComponentBase.
  3. Cut/Paste everything from the @code block into the body of the ExampleComponentBase class.
  4. Tell the Page about it’s new base class. At the top of ExampleComponent.razor, add @inherits ExampleComponentBase before the @page directive.
  5. Fix Dependency Injection. Instead of using the @inherits directive in a Razor page, add an [Inject] Attribute and a {get;set;} to injected dependencies. For example, @inject NavigationManager NavigationManager in a Razor Component would become [Inject] NavigationManager NavigationManager { get; set; } in a code-behind.
  6. Change any private fields accessed by markup to protected. They will need to be protected instead of private since the Razor Component markup is now a sub-class of ExampleComponentBase and thus cannot access private fields.