Skip to content

Blazor Tutorial

Eduardo Fonseca edited this page Nov 19, 2024 · 2 revisions

How to convert pages to use code-behind

Pages and component in Blazor as usually implemented through a file with a ".razor" extension. When the pages need coding, you usually add a "@code { ... }" section. Sometimes you want to further separate the main logic from the actual html, you can do that by using a file with the same name of the page, and with the extension ".razor.cs".

The class in the file must belong to the same namespace, and be a public partial class. A tip to facilitate converting to use code-behind is by using Visual Studio, right click over the "@code" word, select "Quick Actions and Refactorings", and then "Extract block to code behind"

Visual Studio will proceed to create the corresponding ".razor.cs" file, then you just need to fix the compilation issues.

Note: Visual Studio will also incorrectly create a "linked file" in the main project, you must delete the linked file

Clone this wiki locally