Figuring out where to put the code
We have seen examples of writing code directly in the Razor file. I prefer doing that unless the code gets too complicated.
There are four ways we can write our components:
- In the Razor file
- In a partial class
- Inheriting a class
- Only code
In the Razor file
If we are writing a file that is not that complex, it would be nice to not have to switch files when writing components. As we already covered in this chapter, we can use the @code
directive to add code directly to our Razor file. If we want to move the code to a code-behind file, then it is only the directives that we need to change. For the rest of the code, we can just move to the code-behind class. When I started with Blazor, it felt strange to write code and markup in the same file, but I would suggest that you try it out when you develop your web apps.
At work, we started using code-behind but switched to writing code in the .razor file instead and we haven’t looked back since.
But...