📅 June 23, 2021

Razor Components with Partial Class Template

I have been using Blazor recently and by association, utilizing Razor components. You can stick your code directly in the .razor file like so:

@page "/hello"


@code {
    private string text = "Hello";

However, this can get a little unwieldy for more complex components. I like to use a code-behind file for my Razor components when using Blazor. Blazor supports using partial classes. So if you have a Razor component named Foo.razor, your code-behind file can be named Foo.razor.cs and look something like this:

public partial class Foo
    public string Text { get; } = "Hello";

You have the ability to create custom Item Templates in Visual Studio which will generate these files automatically for you. You can view/download my custom Item Template on GitHub here. All you need to do is take those files and place them in the User item template location which can be found in the Visual Studio settings:

Item Template Location

Then, when you use the Add New Item dialog, you should be able to choose the Item Template...

Add New Item

which will create the files!

Generated Files

# productivity | development | dotnet