English
Français

Blog of Denis VOITURON

for a better .NET world

Blazor Code Behind (partial class)

Posted on 2019-11-02

UPDATE: On October 15th 2019, Microsoft announced the partial class support. This article is the update version of the article of october 6th.

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. This file contains a partial class named as the component.

Example:

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

<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>
// File "Counter.razor.cs"
public partial class CounterBase
{
    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-v2.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