English
Français

Blog of Denis VOITURON

for a better .NET world

Blazor Code Behind

Posted on 2019-10-06

UPDATE: On October 15th 2019, Microsoft announced the partial class support. A new version of this article is here.

If, like me, you start developing projects with Blazor, you may prefer to separate your HTML code from your CSharp code.

Indeed, all the examples presented by Microsoft use this format, where the code is injected from the web page via the @code attribute.

<!-- File "Counter.razor" -->
@page "/counter"

<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>

@code {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}

Personally, I prefer to decompose the visual into a .razor file and the CSharp code into a .razor.cs file. It is done without difficulties, by creating:

  1. A Counter.razor file that refers to the class via @inherits.
  2. A CounterBase class that inherits from ComponentBase.

Example:

<!-- File "Counter.razor" -->
@page "/counter"
@inherits CounterBase

<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>
// File "Counter.razor.cs"
public partial class CounterBase : ComponentBase
{
    public int currentCount = 0;

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

Item Template

Creating these two files is often time-consuming, so I created an Item Template for Visual Studio. To use it:

  1. Download this ItemTemplate-RazorComponentCodeBehind.zip.
  2. Copy it into the folder %USERPROFILE%\Documents\Visual Studio 2019\Templates\ItemTemplates.
  3. Restart Visual Studio.

So, you will find a new model of composants.

Item Template

Languages

EnglishEnglish
FrenchFrançais

Follow me

Recent posts