Programmer's Picnic · Learn With Champak
Razor course · Lesson 3 of 4

PageModel and OnGet

Read the explanation, run the sample, and try the exercise.

Separate display and logic

Keep HTML in .cshtml and C# handler logic in .cshtml.cs. This makes larger projects easier to understand.

Pages/Greeting.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
namespace PicnicRazor.Pages;
public class GreetingModel : PageModel
{
    public string Message { get; private set; } = "";
    public void OnGet() => Message = "Hello from C#!";
}

Pages/Greeting.cshtml

@page
@model PicnicRazor.Pages.GreetingModel
<h1>Greeting</h1>
<p>@Model.Message</p>

Open /Greeting. Practice: change the greeting and add another property.

← PreviousNext lesson →