New feature of .NET Core 2 – Razor Pages

By Dawid on (tags: .NET Core 2.0, Pages, razor, categories: code)

If you are looking for another way of building web applications then Razor Pages are for you! Razor Pages are page based programming model for ASP.NET Core MVC and they makes page focused scenarios easier and more productive.

Razor pages are enabled by default in MVC and you don’t have to modify your Startup.cs code in any way. Assembly in which razor pages feature – – should be referenced automatically if you are already using .

Empty Razor Page looks as fallow:

As you can see the only difference from standard ASP.NET MVC page is directive. This turns this page into MVC action which can handle requests directly and no controller is needed.

Razor page with Page Model

While using Razor Pages feature we can specify model which is acting more like a view model rather then regular MVC model. Take a look bellow:

is handler method that is called with GET-request. There is also similar handler available for POST-method and both of these methods have also asynchronous versions  - and

And here is how you can use you model:

Razor page without code behind file

All the code which in previous example was placed in PageModel file can be moved to section like this:

Pages work with all the features of the Razor view engine like layouts, partials, templates, tag helpers, . All of those work in the same way they do for conventional Razor views.

Summary

It’s hard to say how many of you will use Razor Pages. For sure it is lightweight option for those who just want to get started.

If you thing of Razor Pages as of another page scripted framework you are wrong. What are Razor Pages trying to do is:

  • simplify the code for page focused patterns
  • makes dynamic HTML easier in ASP.NET Core MVC
  • they also some how reduce number of directories in MVC project structure
  • use MVC primitives as much as possible