[ASP.NET Core] - Razor Page - Let's think straight

When you need to build a website with the pages you need very quickly, without worrying about complex issues like patterns, security or scaling, Razor Page is the answer

1. Requirements

2. The development pattern

If you are a long-time ASP.NET warrior, you’re surely familiar with the MVC pattern, short for Model-View-Controller. With Razor Page you meet a completely new and extremely simple pattern (so simple there is nothing to learn)

The MVC pattern

mvc pattern

If you want to get familiar with the MVC pattern, you can read [ASP.NET for Beginner] – Part 1 – MVC

The Razor Page ‘pattern’

razor page pattern

3. MVC’s problems

3.1. Fat Controller

Say you have a controller handling tasks related to money transfers between accounts, call it TransactionController

There are 4 basic operations on a row of data: Create-Read-Update-Delete — so far so good, no problem

Bam, you also want to handle phone top-ups, paying electricity, water and internet bills => add methods like NapTheCao, TraTienDien, TraTienNuoc, TraTienInternet. 2 weeks later you want a few more features, all related to transactions.

Over time TransactionController gets longer and longer, and it has officially earned the name Fat Controller.

3.2. Nesting levels

The MVC pattern gives you a folder named Controllers to hold all your controllers. This corresponds to 1 level in the URL

With the transaction example above, your URL looks like: domain/transaction/create

What if you want one level deeper, like domain/transaction/phones/create? You have to either customize the route or create an Area named Transaction and split the related functions into separate controllers.

3.3. Duplicate

For any form, in the mvc pattern there must always be 2 actions matching the 2 verbs, Get and post, and people usually give these 2 actions the same name so they’re easy to tell apart from the other features in the same controller. This is sometimes inconvenient, and you are required to declare the [HttpGet] and [HttpPost] attributes

4. Razor Page Coding conventions

Like MVC, Razor Page also has some coding conventions

Conventions

MVC

RAZOR PAGES

Default View

Index.cshtml

Index.cshtml

return default view

return View();

return Page();

Http Verbs

[HttpGet]
[HttpPost]

OnGet();
OnPost();

Binding data

ViewModel

[BindProperty]

Generate Link

Url.Action(…)

Url.Page(…)

multiple action for form submit

Not built-in

asp-page-handler=“TestHandler”
OnTestHandler()

5. The future is now?

Razor Page, in my judgment, only fits small and medium projects with views that are simple in logic.

As of .NET CORE 2.0, Razor Page still doesn’t support some features MVC has:

  • IActionFilter
  • Output Cache
  • The IgnoreAntiforgeryToken attribute (you can read this github issue to learn how to disable it entirely)