What is Razor Pages and how does it differ from MVC?
4 minintermediateASP.NET-CoreRazor-PagesMVC
Quick Answer
Razor Pages is a page-focused model where each page pairs a `.cshtml` view with a `PageModel` code-behind handling its requests — well-suited to page-centric, form-based UI. MVC separates concerns across Controllers, Models, and Views, better for complex apps with many actions per controller or APIs. Both use Razor and the same underlying framework; Razor Pages reduces ceremony for simple CRUD pages.
Detailed Answer
Razor Pages is a page-based programming model that makes building web UI easier and more productive.
Razor Pages Structure:
Pages/
├── Index.cshtml (View)
├── Index.cshtml.cs (PageModel - code-behind)
├── Privacy.cshtml
├── Privacy.cshtml.cs
└── Shared/
└── _Layout.cshtml
Example Razor Page:
// Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger _logger;
[BindProperty]
public string UserName { get; set; }
public List Products { get; set; }
public IndexModel(ILogger logger)
{
_logger = logger;
}
public void OnGet()
{
Products = GetProducts();
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
// Process form
return RedirectToPage("Success");
}
}
@page
@model IndexModel
Welcome @Model.UserName
Submit
@foreach (var product in Model.Products)
{
@product.Name
}
Key Differences:
| Feature | Razor Pages | MVC |
|---|---|---|
| Structure | Page-centric (cshtml + cs) | Controller-centric |
| Routing | Convention-based on folder | Attribute or conventional |
| Best For | Simple CRUD, forms | Complex apps, APIs |
| Organization | Page-focused | Separated concerns |
| Learning Curve | Easier | Steeper |
| Handler Methods | OnGet, OnPost | Action methods |
MVC Example (for comparison):
// Controller
public class HomeController : Controller
{
public IActionResult Index()
{
var model = new IndexViewModel();
return View(model);
}
[HttpPost]
public IActionResult Index(IndexViewModel model)
{
if (!ModelState.IsValid)
return View(model);
return RedirectToAction("Success");
}
}
When to Use:
- Razor Pages: Simple pages, forms, CRUD operations, page-focused scenarios
- MVC: Complex applications, RESTful APIs, when you need more control over routing