Search code examples
c#razorblazorblazor-client-side

How to split Blazor WASM components code of C# and HTML in different files?


I've some background in Web Development, mostly in ASP MVC and JavaScript with Angular.

Currently, I'm learning Blazor WASM and I'm somehow "confused" because I cannot find any example of how to split the below code into two files.

This is the example code of one component from the default template:

Counter.razor

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

Is it any way to split like into the Angular Web Components? .html and .ts? In this case .razor and .razor.cs?

Counter.razor - HTML

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

Counter.razor.cs - C#

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

I've developed relatively complex SPAs in Angular and sites in ASP MVC and this solution is I'd say okay when your projects are small, but I don't like to mix JS/C# code in the same HTML page. I have faced some complex situations like these ones in the past and it became hard to maintain.

Any idea how to split it? Thanks.


Solution

  • You can create partial classes to separate the code from the HTML:

    [Edit: Thanks to Enet's information] If you name the file [classname].razor.cs, the file becomes a single object in solution explorer. I have learned two things before lunch today; time to slow down.

    If you have a Page (or component) in a Blazor project named Index.razor

    Edit: .Net Core 3.1 is required for partial class support (per Federico Navarrete).

    Create a C# class in the same directory with the same name.

    At first it will not compile, so you have to add the word partial:

    public partial class Index
    {
        ...
    }
    

    I prefer to put all my code in a partial class because .razor pages do not have the drop down menu for methods and properties like a .cs file does.

    enter image description here