Introduction to ASP.NET Core Razor Pages
Hello, I am Fahid and this is part one of an ASP.NET Core Razor Pages tutorial. In this video and in our upcoming videos in this series, we'll discuss everything you need to know to build web applications using ASP.NET Core Razor Pages.
At this point, you might be wondering, we can build a web application using ASP.NET Core MVC as well, so why do we need a different technology like Razor Pages again? Well, we'll discuss the difference between MVC and Razor Pages and the guidelines on when to use one or the other in just a bit.
Prerequisites for the Course
But before that, let's understand the prerequisites to follow along with this course. Install the software required and set up our machine first.
The prerequisites to follow along with this course: you need basic working knowledge of ASP.NET Core, C#, HTML, and CSS. As far as ASP.NET Core is concerned, we discussed these basic concepts in detail in this ASP.NET Core tutorial for beginners course. These basic concepts are equally important for both ASP.NET Core MVC and ASP.NET Core Razor Pages. We'll be touching upon these concepts as we progress through this course, but if you want the detailed explanation, please check out this beginner's course first.
Setting Up the Development Environment
Next, let's install the software required and set up our machine. We need two softwares: Visual Studio and the .NET Core SDK. Visual Studio 2019 is now released and we'll be using this as the editor. The Community Edition is free and you can download it from this URL right here. I'll have this link available both in the description of this video as well as on my blog.
Once you are on this site, click on the drop-down here and you can download Community Edition. So when you click on this button, an executable will be downloaded. Run it as an administrator and then follow the simple on-screen instructions to install Visual Studio 2019.
While installing Visual Studio, on this workload screen, make sure this workload—ASP.NET and web development—is selected. As of this recording, the latest stable version of .NET Core is 3.0, and this is the version we'll use in this course. To download and install the .NET Core SDK, visit this URL right here. Notice the latest stable version is 3.0. 3.1 is still in preview. So click on this link, download, and follow the on-screen instructions.
Creating Your First Razor Pages Project
After the required software is installed, launch Visual Studio 2019 and we want to create a new project, so click this button. What we want to create is an ASP.NET Core Web Application, so select this template and then click Next. Provide a name for the project, let's name it RazorPagesTutorial. On my machine, I'm going to store it in C:\projects folder, and then click Create.
On the screen, make sure .NET Core is selected and we want to use ASP.NET Core 3.0. And the template that we want to use is this. This creates a web application using Razor Pages. On the right here, do not select any authentication, check this checkbox, Configure for HTTPS, and then finally click Create.
There we go, our Razor Pages project is successfully created.
Project Structure and Basic Routing
If we take a look at the Solution Explorer, notice this project structure is not very different from an ASP.NET Core MVC project structure. One primary difference that we see here is, in an ASP.NET Core MVC project, we'll have Models, Views, and Controllers folders. In this Razor Pages project, we have a Pages folder, and this is the folder where all the Razor Pages will live.
The rest of the infrastructure, that is the rest of the files and folders like this wwwroot, appsettings, Program, and Startup.cs are the same in both the projects. And if we take a look at the Pages folder, notice at the moment we've got two Razor Pages: Index and Privacy. For now, let's run this project by pressing Ctrl+F5 and see what we have got so far.
Notice in the address bar we have our application root URL and then we have a web page displaying this text, "Welcome." This web page is this index.cshtml Razor Page. At this point you might be wondering how is the index Razor Page served when we navigate to the root application URL? We'll answer that question in our upcoming videos. For now, let's navigate to /index and see what happens. We still see the same index Razor Page. So this URL /index is mapped to this Razor Page, index, within the Pages folder.
In addition to the index, we also have this privacy Razor Page. So if we navigate to /privacy, then this privacy Razor Page will be served. There we go. If we go back to /index, we see the index Razor Page. A Razor Page has the extension .cshtml. CS because the programming language is C#. When routing to these Razor Pages this extension .cshtml is not required in the URL.
Anatomy of a Razor Page and its Page Model
A Razor Page is a combination of two files. Notice when I expand this little tree node here, we see another file with the same name, but ends with the extension .cs. So this first file that has the extension .cshtml is the display template, and the second file that ends with the extension .cs is called the Page Model.
Let's open both the files. Notice this index Razor Page display template is not very different from an ASP.NET Core MVC view file. What makes it different is this @page directive. This directive tells ASP.NET Core that this is a Razor Page. And then we have this @model directive. As the name implies, this directive specifies the model for this display template, and at the moment, it is IndexModel. And this is the corresponding Page Model class that we have in this file, index.cshtml.cs.
Notice the name of the class has the same name as the Razor Page, Index, and then it ends with the word Model. So this Page Model class is the model for the display template, and that is specified right here using this @model directive. This class inherits from the built-in PageModel class.
Just like ASP.NET Core MVC, Razor Pages also support dependency injection. Notice the built-in ILogger service is injected into this class using its constructor. We can use this ILogger service to log to various logging destinations. In addition to dependency injection and logging, other ASP.NET Core features like reading from various configuration sources, model binding, model validation, etc. are also supported.
Practical Example: Modifying the Index Page
At the moment, the index Razor Page displays this text, "Welcome," and this is present in the display template right here. Notice the model for this display template is IndexModel, but we are not using it anywhere within this display template. What we want to do right now is display the string "Hello World" instead of "Welcome," and we want that string to come from the model class.
So within the model class, let's include a public property. This is going to be of type string and let's call it Message. Notice at the bottom here we have a method with name OnGet. When a GET request is issued to this index Razor Page, this is the method that handles that HTTP GET request. As you might have guessed by now already, we can also include a similar OnPost method, and that handles the HTTP POST request. We'll discuss handling POST in our upcoming videos. For now, we want to initialize this public property with the string "Hello World". Let's do that inside this OnGet method.
This Message property is now available in the display template. To access it from the display template, just use @Model with an uppercase M and notice when I press dot, we see the Message property. Let's save all these changes and reload the browser page. There we go.
In addition to "Hello World", let's also display the current time. So let's set the message to: "Hello World, the time now is..." To this, we want to append the current date-time, so DateTime.Now.ToLongTimeString(). Let's save and take a look at the browser. There we go. We see the current time. Every time we reload the page, we see the updated time.
If we compare ASP.NET Core MVC with Razor Pages, in MVC, we have three components: Model, View, and Controller. In Razor Pages, we have just two: the display template and the corresponding Page Model class. This Page Model class is like both the controller and the model. It is this OnGet method that handles an HTTP GET request from the browser, so this is like the controller action. And this public property makes the data available to the display template, so it's like the model. We can have more than one public property; all the public properties make up the model. And these methods, OnGet and OnPost, that handle GET and POST respectively, are the controller actions. So this Page Model class is like both the controller and the model, and the display template is like the view in MVC.
Razor Pages is a new technology to build page-focused web applications quicker and more efficiently. Razor Pages are introduced in .NET Core 2.0. It is lightweight, flexible, and provides the developer the full control of the rendered HTML. In some respects, Razor Pages are similar to the classic ASP.NET Web Forms framework. In ASP.NET Web Forms, we have an aspx page and a code-behind class. The aspx page contains the HTML and controls the visual part. The code-behind class contains the server-side C# or Visual Basic code that handles the page events.
For example, if you have a web form with name WebForm1, it's actually a pair of files: WebForm1.aspx, which is the display template, and WebForm1.aspx.cs, and this is the code-behind class. Similarly, each Razor Page is also a pair of files. .cshtml is the template, so it contains the HTML and Razor syntax. .cshtml.cs, this is the Page Model class, and it contains the server-side C# code that handles the page events and provides the data the display template needs.
In-Depth Comparison: MVC vs. Razor Pages
Now let's compare MVC and Razor Pages. With MVC, we have three main components: Model, View, and Controller. It is the controller in the MVC design pattern that receives the request and handles it. The controller creates the model. The model has the classes that describe the data. In addition to creating the model, the controller also selects a view and passes the model object to the view. The view contains the presentation logic to display the model data provided to it by the controller.
In MVC, in addition to model, view, and controller, we also have actions and view models. If we are building a fairly complex web portal, chances are we may end up with controllers that work with many different dependencies and view models and return many different views. In short, we may end up with large controllers with many, many actions that are not related to each other in any way. This not only results in unnecessary complexity but also violates the fundamental principles of programming like Single Responsibility Principle and Open-Closed Principle.
On the other hand, a Razor Page is just a pair of files: a display template and the corresponding Page Model class. As the name implies, the display template contains the HTML. The Page Model class contains the server-side code and combines the responsibility of a controller and a view model. Everything we put in the Page Model class is related to the page, so unlike controllers in MVC, bloating the Page Model class with unrelated methods is almost impossible. Since the Page Model class and the display template are at one place and closely related to each other, building individual pages with Razor Pages is fairly straightforward while still using all the architectural features of ASP.NET Core like dependency injection, middleware components, model binding, validation, etc. If all of this is a bit confusing, please don't worry, it will become much clearer as we progress through the course.
When to Use Razor Pages vs. MVC
So, bottom line, the recommendation from Microsoft is to use Razor Pages if we are building a web UI that is web pages, and ASP.NET Core MVC if we are building a Web API. Whether you use ASP.NET Core MVC or Razor Pages for building a web application, there's no difference from a performance standpoint. It's also possible to combine both the patterns, that is ASP.NET Core MVC and Razor Pages, in a given single ASP.NET web application.
What to learn, MVC or Razor Pages? I personally think an ASP.NET Core developer must have both the skills, so learn both. If you're starting to learn ASP.NET Core, I suggest start with our ASP.NET Core tutorial for beginners course, and then this Razor Pages tutorial. That's it in this video. Thank you for listening.