Comparing Razor Pages with ASP.NET MVC

laptop

Razor Pages is the preferred way to create page or form-based applications in ASP.NET Core. From the documentation, “Razor Pages can make programming page-oriented scripts easier and more efficient than using controllers and views.” If your ASP.NET MVC application makes heavy use of views, you might consider switching from actions and views to Razor Pages.

A typical strictly typed view-based MVC application will use a controller to store one or more actions. The controller will interact with a domain or data model and create an instance of the viewmodel class. This viewmodel class is then passed to the view associated with that action. Using this approach in conjunction with the default folder structure of MVC applications, adding a new page to the application requires modifying the controller in one folder, the view in a subfolder in another folder, and the viewmodel in yet another folder.

Razor Pages group the action (now handler) and the view model (called PageModel) in one class and associate that class with the view (called Razor Page). All razor Pages go into the Pages folder in the root of the ASP.NET Core project. Razor Pages use a routing convention based on their name and location in this folder. Handlers behave just like action methods, but have an http command that they handle in their name (such as OnGet). They also don’t necessarily have to return, as the default assumption is that they return the page they are associated with. This tends to make Razor Pages and their handlers smaller and more focused, while making it easier to find and work with all the files needed to add or modify a particular part of the application.

As part of the transition from ASP.NET MVC to ASP.NET Core, teams should consider whether to migrate controllers and views to ASP.NET Core controllers and views or to Razor Pages. The former will likely require a little less overall effort, but will not allow the team to take advantage of the benefits of Razor Pages over traditional view-based file organization.