How-To: Use Blazor Code-Behind File

In Blazor, sometimes our page code becomes large and cumbersome. Rather than keep all of the HTML markup and C# code in the same .razor file, we can split our markup and code into separate files. Blazor supports creating code-behind files for the .razor file (similar to other .NET technologies like WinForms, ASP.NET, WPF, etc).

The code-behind file can encapsulate all of our C# code and be associated with the .razor file for easy access in our IDE. The code class uses the partial keyword to separate the class’s logic out into another file. Let’s see how this is done…

First, we must have a Blazor project. Either open an existing Blazor project, or please follow the steps in the How-To: Create Blazor WASM Project article to create a new one. For this article, we called the project: Blazor.HowTo.

Then, we must work with a page. If we don’t already have a page, we can create one using the steps in the How-To: Create New Page in Blazor article. For this article, we named the page: ‘Page3.razor’.

Define Markup File

Starting with the default markup created in the Page3.razor file. Let’s make the following changes:

@page "/page-3"

<h3>Binary-Decimal Converter [code-behind]</h3>
<form class="form-row col-lg-4 col-md-12">
    <div class="form-group col-12">
        <label for="binary">Binary:</label>
        <input type="text" class="form-control" id="binary"
               placeholder="Enter binary number" @bind-value="@binary">
    <div class="form-group col-12">
        <input id="convert-decimal" type="button"
               value="Convert to Decimal" @onclick=ConvertToDecimal />
    <div class="form-group col-12">
        <label>Decimal Result: @result</label>

First, this markup is the same as we created for the How-To: Add Two-Way Binding to Blazor Page article. It defines the components to input binary numbers and convert them to decimal. (If you need detailed description of the markup, please read that article).

Then, notice that the @page directive defines our route for “/page-3”.

And, we kept the same databinding to member variables and methods as we had before. At this point, these bindings are invalid because these members don’t exist yet.

Finally, we removed the @code block altogether from this file. While that isn’t required, we wanted to keep this file as clean as possible, and not confuse folks with code in both places.

Create Code-Behind File

Now, we will follow these steps to create a new C# file.

  1. Right-click on our Pages folder in the Solution Explorer (this will bring up the context menu).
  2. Select the ‘Add > Class…’ menu option.
  3. In the ‘Add New Item’ dialog, enter our new class name: ‘Page3.razor.cs’.
Fig 1 – Add New Item Dialog
  1. Press the ‘Add’ button.
  2. For Visual Studio to tie this code-behind file with its associated .razor page, we must use the full name of the file and append ‘.cs’ to the end.
    • Visual Studio uses this convention to make the code file a child of the .razor file.
    • While this is not technically required for the code-behind class to be found, it does logically tie those two files together and helps unclutter the items in the Solution Explorer.
Fig 2 – Code-Behind File in Solution Explorer

With the code file in place, let’s add our class code to it:

using System;

namespace Blazor.HowTo.Pages
    public partial class Page3
        string binary;
        string result;

        void ConvertToDecimal()
                result = Convert.ToInt32(binary, 2).ToString();
                result = "Error: not a valid binary number.";

First, we change the class definition to use the partial keyword and name the class Page3 to match the type generated by Razor for the page. The partial keyword breaks up the implementation of a class between multiple source files. This is used extensively in code generation – as the generated code is in its own file that can be continuously over-written, and developer code lives in our own file.

Then, we define the local member variables for the input text in binary and the output text in result. These are used to bind with our input controls.

Finally, we have the ConvertToDecimal method which performs the conversion. This method is bound to the convert button’s @onclick event.

With this code in place, we can now build our project again. The code from our Page3 class merges with the code Razor generates to represent the page, so the end result is the same as if the code in the file were present in the @code block.

Let’s run the application, navigate to page-3, and test out the conversion logic:

Fig 3 – Page with Separate Markup and Code-Behind

In conclusion, Blazor provides us with a mechanism for separating our code from markup. This can be good for pages with complex logic so that we don’t require our markup and code to live in a single file. But code-behind is not required for .razor pages, if we prefer the simpler style of everything in a single file. It is really a matter of preference and style.

There are other strategies for separating code from markup which are even better for the testability of our logic (like moving the code to a separate class file, and using the MVVM pattern), which we will review in upcoming articles.

One thought on “How-To: Use Blazor Code-Behind File

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s