...

/

Using Code-Behind in Razor Components

Using Code-Behind in Razor Components

Learn how to split markup from the code in Razor components.

In all examples that we’ve used so far, the Razor component code was placed in the block under the @code directive. However, if we want to apply the separation of concerns and keep business logic separate from the display logic, we may want to move our code into a separate file. We can achieve this in Blazor using code-behind files.

Press + to interact
Razor component code-behind
Razor component code-behind

There are two ways we can apply code-behind in Blazor, via partial classes and via base classes.

We will cover them both in this lesson. We have the following project set up for this purpose:

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
Setup with code-behind examples

Using code-behind as a partial class

In the setup above, we ...