Learn ASP.NET Core Β· 10/13

Building User Interfaces with Razor Pages

7 min read

Course: ASP.NET Core

Topic: Building User Interfaces with Razor Pages


1. Introduction to Razor Pages: Page-Focused Server-Side UI

🧐 Definition & The Problem

In the early days of ASP.NET MVC, creating a simple "Contact Us" page required a surprising amount of jumping around. You needed a Controller to handle the route, a Model to hold the data, and a View to display it. These files were often located in completely different folders.

The Problem: For page-focused scenarios (where a URL maps directly to a specific view), the Model-View-Controller (MVC) pattern can feel like "over-engineering." It scatters related logic across the project structure.

The Solution: Razor Pages. Introduced in ASP.NET Core 2.0, Razor Pages is a "page-first" framework. It encapsulates the User Interface (View) and the Logic (Model) for a single page into a unified pair of files. It is built on top of the MVC primitives, so you still have all the power of ASP.NET Core, but with a folder structure that makes sense for web pages.

πŸ› οΈ Hands-On: Getting Started

In 2026, creating a Razor Pages app is the default standard for server-side HTML rendering in .NET.

Step 1: Create a new project
Using the .NET CLI (Command Line Interface), run:

bash
dotnet new webapp -n RazorFreeCodeCamp
cd RazorFreeCodeCamp

Step 2: Understand the Structure
Instead of Controllers and Views folders, you have a Pages folder.

  • Pages/Index.cshtml β†’ The HTML template.
  • Pages/Index.cshtml.cs β†’ The C# logic (code-behind).

Step 3: Run it

bash
dotnet watch run

dotnet watch will automatically reload your browser when you save changes.

πŸ’‘ Did You Know?
The Razor syntax (@) was invented by Microsoft to minimize "keystroke friction." Before Razor, developers used the "ASPX" engine which looked like <%= var %>. Razor's parser is smart enough to detect where C# ends and HTML begins without needing explicit closing tags in many cases!


2. Page Models: Handling GET and POST Requests Efficiently

🧐 Definition & The Problem

In standard HTML, a page is just static text. If you want to process a form submission, you need a server endpoint. In older frameworks, you might have pointed a <form> to a separate generic handler file.

The Problem: Mixing C# logic directly inside HTML files (like in classic ASP or PHP) creates "Spaghetti Code"β€”it's hard to read, test, and maintain.

The Solution: The PageModel. This is a C# class that inherits from PageModel. It acts as a mini-controller specifically for one page. It separates the "display" (HTML) from the "processing" (C#).

πŸ’» Code Example: The "Contact Us" Page

Let's build a simple form handling flow.

The View (Contact.cshtml):

html
@page
@model RazorFreeCodeCamp.Pages.ContactModel
@{
    ViewData["Title"] = "Contact Us";
}

<h2>Contact Us</h2>

<!-- We show a success message if it exists -->
@if (!string.IsNullOrEmpty(Model.Message))
{
    <div class="alert alert-success">@Model.Message</div>
}

<form method="post">
    <!-- The 'asp-for' tag helper binds input to the property -->
    <label>Your Name:</label>
    <input asp-for="UserName" class="form-control" />
    
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

The Logic (Contact.cshtml.cs):

csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorFreeCodeCamp.Pages
{
    public class ContactModel : PageModel
    {
        // [BindProperty] connects the Form data to this C# property automatically
        [BindProperty]
        public string UserName { get; set; } = string.Empty;

        public string Message { get; set; } = string.Empty;

        // OnGet executes when the user simply visits the URL
        public void OnGet()
        {
            // Page initialization logic goes here
        }

        // OnPost executes when the user submits the form via POST
        public void OnPost()
        {
            if (!string.IsNullOrEmpty(UserName))
            {
                Message = $"Thanks for contacting us, {UserName}!";
            }
        }
    }
}

πŸ”‘ Key Concepts

  1. Handlers: Methods like OnGet() and OnPost() are called "Handler Methods." They automatically match the HTTP Verb (GET, POST, PUT, DELETE).
  2. [BindProperty]: This attribute enables Model Binding. It automatically takes the value from the HTTP Form input named UserName and assigns it to the C# property UserName. No more Request.Form["UserName"]!

πŸ§ͺ Industry Standard: Always use OnPostAsync if you are doing database operations (like saving the contact info) to keep your server responsive under high load.


3. Tag Helpers: Seamlessly Connecting HTML to C# Code

🧐 Definition & The Problem

In older ASP.NET MVC versions, we used "HTML Helpers" to generate links and forms. They looked like this:
@Html.ActionLink("Home", "Index", "Home")

The Problem: This syntax breaks the flow of writing HTML. It looks like C# code injected weirdly into markup, and front-end designers (who know HTML/CSS but not C#) find it confusing to style.

The Solution: Tag Helpers. Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. They look exactly like standard HTML tags but have special attributes (usually starting with asp-).

πŸ› οΈ Common Tag Helpers

Tag Helper Standard HTML What it does
Anchor <a asp-page="/Index">Home</a> Generates the correct URL (href="/Index") based on your routing configuration.
Form <form method="post"> Automatically generates a hidden Anti-Forgery Token to prevent security attacks (CSRF).
Input <input asp-for="Email" /> Sets id, name, type, and validation attributes based on the C# property data type.
Validation <span asp-validation-for="Email"></span> Displays error messages if the Model Validation fails.

πŸ’» Example: A Robust Link

html
<!-- Old Way (Html Helper) - Confusing for designers -->
@Html.ActionLink("Edit Profile", "Edit", new { id = 5 }, new { @class = "btn btn-primary" })

<!-- New Way (Tag Helper) - Readable HTML -->
<a asp-page="/Edit" asp-route-id="5" class="btn btn-primary">
    Edit Profile
</a>

🧠 Imagination Exercise: Think of Tag Helpers as "Server-Side Decorators." The HTML tag is the cake. The Tag Helper is the baker who steps in before the cake is served to the browser, adding the correct frosting (attributes) and filling (content) based on the recipe (C# code).


4. DRY UI: Working with Layouts and Partial Views

🧐 Definition & The Problem

Most websites have a common header, footer, and navigation bar.

The Problem: If you copy-paste the navigation HTML into every single .cshtml page, you violate the DRY (Don't Repeat Yourself) principle. If you need to change a menu item, you have to edit 50 files.

The Solution: Layouts and Partial Views.

πŸ—οΈ The Layout File (_Layout.cshtml)

This acts as the master template. It contains the <html>, <head>, and <body> tags.

html
<!DOCTYPE html>
<html>
<head>
    <title>@ViewData["Title"] - My App</title>
</head>
<body>
    <header>
        <nav>
            <a asp-page="/Index">Home</a>
            <a asp-page="/Privacy">Privacy</a>
        </nav>
    </header>

    <main role="main" class="container">
        <!-- This is where the individual page content is injected -->
        @RenderBody()
    </main>

    <footer>
        &copy; 2026 - RazorFreeCodeCamp
    </footer>
    
    <!-- Renders scripts required by specific pages -->
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

🧩 Partial Views

A Partial View is a reusable chunk of HTML (like a "User Profile Card" or a "Comment Box") that can be embedded inside other pages.

Creating a Partial (_UserCard.cshtml):

html
@model RazorFreeCodeCamp.Models.User
<div class="card">
    <h3>@Model.Name</h3>
    <p>Status: @Model.Status</p>
</div>

Using the Partial:
You can use the <partial> tag helper to render it anywhere.

html
<!-- Inside Index.cshtml -->
<partial name="_UserCard" model="currentUser" />

βš™οΈ The _ViewStart.cshtml File

This is a special file. The code inside _ViewStart.cshtml is executed before every view in that folder.

csharp
@{
    // Automatically sets the Layout for every page so you don't have to
    Layout = "_Layout";
}

πŸ“’ Interesting Fact: The underscore prefix in _Layout.cshtml and _ViewStart.cshtml is a convention. In ASP.NET, files starting with _ are typically not servable directly by the browser (you can't navigate to /pages/_Layout). They are strictly for internal use!


πŸ”— References & Further Reading

Challenge

Challenge Instructions

You are tasked with creating a user registration page in an ASP.NET Core Razor Pages application. You will need to implement both the C# logic in the PageModel (Register.cshtml.cs) and the UI markup in the Razor view (Register.cshtml).

To adhere to the DRY principle, you will also create and use a partial view (_FormFieldPartial.cshtml) to render a standard form field containing a label, input, and validation message.

Register.cshtml.cs Requirements:

  1. Define a public nested class named InputModel that will serve as the view model. It should contain public string properties for Email and Password.
  2. Create a public property of type InputModel named Input. Decorate this property with the [BindProperty] attribute to enable model binding for POST requests.
  3. Implement an empty OnGet() handler method.
  4. Implement the OnPost() handler method. It should simply return the current page.

Register.cshtml Requirements:

  1. In a Razor code block, set the Layout for this page to "_Layout".
  2. Create an HTML <form> that submits data using the POST method. The form should contain an anti-forgery token.
  3. Inside the form, use the <partial> tag helper twice to render the _FormFieldPartial.cshtml view. The first instance should be for the Email property and the second for the Password property of your InputModel.
  4. Add a submit button to the form.

_FormFieldPartial.cshtml Requirements:

  1. This partial view must be strongly typed to accept a Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression object.
  2. Within a <div>, create three elements:
    • A <label> element bound to the model expression.
    • An <input> element bound to the model expression.
    • A <span> element for displaying validation messages, also bound to the model expression.

Expected result

Expected Output Description

Your completed code should correctly implement a Razor Page for user registration using a PageModel, model binding, tag helpers, and a partial view.

Register.cshtml.cs

csharp
// File: Pages/Register.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApp.Pages
{
    public class RegisterModel : PageModel
    {
        [BindProperty]
        public InputModel Input { get; set; }

        public class InputModel
        {
            public string Email { get; set; }
            public string Password { get; set; }
        }

        public void OnGet()
        {
        }

        public IActionResult OnPost()
        {
            // In a real app, you would validate ModelState and save the user.
            return Page();
        }
    }
}

Register.cshtml

csharp
// File: Pages/Register.cshtml
@page
@model WebApp.Pages.RegisterModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{
    Layout = "_Layout";
}

<h1>Register</h1>

<form method="post">
    <partial name="_FormFieldPartial" for="Input.Email" />
    <partial name="_FormFieldPartial" for="Input.Password" />
    <button type="submit">Register</button>
</form>

_FormFieldPartial.cshtml

csharp
// File: Pages/Shared/_FormFieldPartial.cshtml
@using Microsoft.AspNetCore.Mvc.ViewFeatures
@model ModelExpression

<div>
    <label asp-for="@Model"></label>
    <input asp-for="@Model" class="form-control" />
    <span asp-validation-for="@Model" class="text-danger"></span>
</div>
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.