Examples
C# Razor Page App
Building a Razor Page App
C# Razor Page app creates page-based web UIs.
Introduction to C# Razor Page Apps
C# Razor Page Apps provide a streamlined approach to creating web applications with a page-based architecture. Razor Pages focus on the page model, making it easier to organize code and manage functionality. This tutorial will guide you through the essentials of creating a C# Razor Page app, including structure, routing, and basic data handling.
Setting Up a Razor Page App
To get started with a Razor Page app, you'll need to set up your development environment. This involves installing the .NET SDK and using Visual Studio or Visual Studio Code.
Once your environment is ready, create a new Razor Pages project using the following command in the terminal:
Understanding the Project Structure
After creating a new Razor Pages project, you'll notice several key components:
- Pages: Contains Razor pages (.cshtml files) and related logic.
- wwwroot: Houses static files like CSS, JavaScript, and images.
- Startup.cs: Configures services and the app's request pipeline.
Creating a Simple Razor Page
Let's create a simple Razor Page to display a welcome message. Add a new Razor Page by right-clicking the Pages folder, selecting Add -> Razor Page, and naming it Welcome.
Edit the Welcome.cshtml file to include the following markup:
Adding a Page Model
The page model in Razor Pages is responsible for handling page logic. It is typically defined in a code-behind file with the .cs extension.
For our Welcome page, create a Welcome.cshtml.cs file:
Routing in Razor Pages
Razor Pages use a convention-based routing approach. The URL path is derived from the file's location within the Pages folder. For example, /Pages/Welcome.cshtml would be accessed at /Welcome.
Running the Razor Page App
To run your Razor Page app, use the following command in the terminal:
Open your web browser and navigate to http://localhost:5000/Welcome to see your Razor Page in action.
Congratulations, you've created a basic C# Razor Page app!
Examples
- Previous
- Real-Time Chat
- Next
- API Testing