Using Code-Behind Files with Razor Pages
Learn about creating a razor page illustrated through creating a suppliers list page.
We'll cover the following
Sometimes, it is better to separate the HTML markup from the data and executable code because it is more organized. Razor Pages allows us to do this by putting the C# code in code-behind class files. They have the same name as the .cshtml
file but end with .cshtml.cs
.
Creating a Razor Page for a list of suppliers
We will now create a Razor Page that shows a list of suppliers. In this example, we are focusing on learning about code-behind files. Next, we will load the list of suppliers from a database, but for now, we will simulate that with a hardcoded array of string
values:
Step 1: In the Pages
folder, add a new file named Suppliers.cshtml
:
If you are using Visual Studio 2022, the project item template is named
RazorPage - Empty
, and it creates both a markup file and a code-behind file namedSuppliers.cshtml
andSuppliers.cshtml.cs
respectively.If you are using Visual Studio Code, you must create two new files named
Suppliers.cshtml
andSuppliers.cshtml.cs
manually.
Step 2: In Suppliers.cshtml.cs
, add statements to define a property to store a list of supplier company names and populate it when an HTTP GET request for this page is made, as shown in the following code:
Get hands-on with 1400+ tech skills courses.