Razor Pages is a page-based programming model introduced in ASP.NET Core 2.0. It simplifies the development of web user interfaces by organizing code around individual pages rather than controllers and views. This makes it easier to build and maintain web applications, especially for those familiar with page-centric frameworks.
Key benefits of Razor Pages include:
A Razor Page consists of two parts: a Razor markup file (.cshtml) and a code-behind file (.cshtml.cs).
1. Create the Razor Page: In your project's "Pages" folder, create a new file named "About.cshtml".
<!-- Pages/About.cshtml --> @page <h1>About Us</h1> <p>This is a simple About page created using Razor Pages.</p> <p>@Model.Message</p>
2. Create the Code-Behind File: In the same folder, create a new file named "About.cshtml.cs".
// Pages/About.cshtml.cs using Microsoft.AspNetCore.Mvc.RazorPages; namespace YourProjectName.Pages { public class AboutModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Welcome to the About page!"; } } }
Explanation:
@page
AboutModel
PageModel
OnGet()
Model.Message
Message
Razor Pages make it easy to handle form submissions using OnPost() methods.
OnPost()
1. Create the Razor Page: Create a file named "Contact.cshtml".
<!-- Pages/Contact.cshtml --> @page <h1>Contact Us</h1> <form method="post"> <label for="name">Name:</label> <input type="text" id="name" name="Name" /><br /><br /> <label for="email">Email:</label> <input type="email" id="email" name="Email" /><br /><br /> <button type="submit">Submit</button> </form> <p>@Model.Message</p>
2. Create the Code-Behind File: Create a file named "Contact.cshtml.cs".
// Pages/Contact.cshtml.cs using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace YourProjectName.Pages { public class ContactModel : PageModel { [BindProperty] public string Name { get; set; } [BindProperty] public string Email { get; set; } public string Message { get; set; } public void OnGet() { } public void OnPost() { Message = $"Thank you, {Name}! We will contact you at {Email}."; } } }
[BindProperty]
Name
Email
Razor Pages use file-based routing. The URL of a page is determined by its location in the "Pages" folder.
You can customize the route using the @page directive.
<!-- Pages/MyCustomPage.cshtml --> @page "/custom-route" <h1>Custom Route Page</h1>
This page will be accessible at /custom-route.
/custom-route
Razor Pages provide a streamlined approach to building web applications with ASP.NET Core. Their simplicity and organization make them an excellent choice for many projects.
Comments - Beta - WIP