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:
dotnet new webapp -n RazorFreeCodeCamp
cd RazorFreeCodeCampStep 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
dotnet watch rundotnet 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):
@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):
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
- Handlers: Methods like
OnGet()andOnPost()are called "Handler Methods." They automatically match the HTTP Verb (GET, POST, PUT, DELETE). [BindProperty]: This attribute enables Model Binding. It automatically takes the value from the HTTP Form input namedUserNameand assigns it to the C# propertyUserName. No moreRequest.Form["UserName"]!
π§ͺ Industry Standard: Always use
OnPostAsyncif 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
<!-- 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.
<!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>
© 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):
@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.
<!-- 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.
@{
// Automatically sets the Layout for every page so you don't have to
Layout = "_Layout";
}π’ Interesting Fact: The underscore prefix in
_Layout.cshtmland_ViewStart.cshtmlis 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:
- Define a public nested class named
InputModelthat will serve as the view model. It should contain public string properties forEmailandPassword. - Create a public property of type
InputModelnamedInput. Decorate this property with the[BindProperty]attribute to enable model binding for POST requests. - Implement an empty
OnGet()handler method. - Implement the
OnPost()handler method. It should simply return the current page.
Register.cshtml Requirements:
- In a Razor code block, set the
Layoutfor this page to"_Layout". - Create an HTML
<form>that submits data using thePOSTmethod. The form should contain an anti-forgery token. - Inside the form, use the
<partial>tag helper twice to render the_FormFieldPartial.cshtmlview. The first instance should be for theEmailproperty and the second for thePasswordproperty of yourInputModel. - Add a
submitbutton to the form.
_FormFieldPartial.cshtml Requirements:
- This partial view must be strongly typed to accept a
Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpressionobject. - 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.
- A
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
// 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
// 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
// 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>