How to create "Code Behind" Blazor Components with VS 2019?

Since October 2019, it is possible to use partial classes. So today you can name the class in the code-behind file like this:

public partial class Foo : ComponentBase
{
    protected override Task OnInitializedAsync()
    {
        // do stuff
    }
}

If you name the class file Foo.razor.cs it will appear under the Foo.razor razor file in solution explorer.


UPDATE: This is now possible: https://stackoverflow.com/a/59470941/1141089

Currently, the "code-behind" and .razor view can't share the same name.

So when you have Foo.razor.cs and Foo.razor it is seen as the same file and thus causes a collision.

Workaround for now: Rename your Foo.razor.cs to FooBase.cs (or something else).

Then in your Foo.razor, add @inherits FooBase

There is a GitHub issue regarding this here: https://github.com/aspnet/AspNetCore/issues/5487

Tags:

Blazor