How To Use Razor Pages In ASP.NET Core 2.0

Razor Pages are introduced in ASP.NET Core 2.0 to make building simple web applications quicker and are a good way to play with various ASP.NET Core concepts like Razor, Layout Pages and Tag Helpers etc. 

In this article, we will learn how to use Razor Pages in ASP.NET Core 2.0.
 
Solution

Create an empty project and amend Startup.cs to add services and middleware for MVC.

  1. public void ConfigureServices(  
  2.     IServiceCollection services)  
  3. {  
  4.     services.AddSingleton<IMovieService, MovieService>();  
  5.     services.AddMvc();  
  6. }  
  7.   
  8. public void Configure(  
  9.     IApplicationBuilder app,   
  10.     IHostingEnvironment env)  
  11. {  
  12.     app.UseMvc();  
  13. }  

Add a service and domain model (implementation of IMovieService is just in-memory list in sample source code).

  1. public class Movie  
  2. {  
  3.     public int Id { get; set; }  
  4.     public string Title { get; set; }  
  5.     public int ReleaseYear { get; set; }  
  6.     public string Summary { get; set; }  
  7. }      
  8. public interface IMovieService  
  9. {  
  10.     List<Movie> GetMovies();  
  11.     Movie GetMovie(int id);  
  12.     void AddMovie(Movie item);  
  13.     void UpdateMovie(Movie item);  
  14.     void DeleteMovie(int id);  
  15.     bool MovieExists(int id);  

Add input and output models (to receive and send data via property bindings).

  1. public class MovieInputModel  
  2. {  
  3.     public int Id { get; set; }  
  4.     [Required]  
  5.     public string Title { get; set; }  
  6.     public int ReleaseYear { get; set; }  
  7.     public string Summary { get; set; }  
  8. }  
  9.   
  10. public class MovieOutputModel  
  11. {  
  12.     public int Id { get; set; }  
  13.     public string Title { get; set; }  
  14.     public int ReleaseYear { get; set; }  
  15.     public string Summary { get; set; }  
  16.     public DateTime LastReadAt { get; set; }  
  17. }  

Add a folder called Pages and add Index, _Layout, _ViewImports and _ViewStart pages to it. These pages are no different than MVC. Also, add a folder named Movies to the CRUD pages.

ASP.NET Core

Add 4 new RazorPage items to the Movies folder, called Index, Create, Edit, and Delete. These will add .cshtml and .cshtml.cs files.

ASP.NET Core

Each of these pages will have our IMovieService injected via constructor injection e.g.,

  1. private readonly IMovieService service;  
  2.   
  3. public IndexModel(IMovieService service)  
  4. {  
  5.     this.service = service;  
  6. }  

Modify the Index.cshtml.

  1. @page  
  2. @model IndexModel  
  3. @{  
  4. }  
  5.   
  6. <h2>Movie Listing</h2>  
  7.   
  8. <div>  
  9.     <a asp-page="/Index">Home</a> |   
  10.     <a asp-page="./Create">Add New</a>  
  11. </div>  
  12.   
  13. <table>  
  14.     <thead>  
  15.         <tr>  
  16.             <th>Title</th>  
  17.             <th>Year</th>  
  18.             <th></th>  
  19.             <th></th>  
  20.             <th></th>  
  21.         </tr>  
  22.     </thead>  
  23.     <tbody>  
  24.         @foreach (var item in Model.Movies)  
  25.         {  
  26.             <tr>  
  27.                 <td>@item.Title</td>  
  28.                 <td>@item.ReleaseYear</td>  
  29.                 <td><a asp-page="./Edit" asp-route-id="@item.Id">Edit</a></td>  
  30.                 <td><a asp-page="./Delete" asp-route-id="@item.Id">Delete</a></td>  
  31.             </tr>  
  32.         }  
  33.     </tbody>  
  34. </table>  

Modify the Index.cshtml.cs.

  1. public List<MovieOutputModel> Movies { get; set; }  
  2.   
  3. public void OnGet()  
  4. {  
  5.     this.Movies = this.service.GetMovies()  
  6.                               .Select(item => new MovieOutputModel  
  7.                               {  
  8.                                   Id = item.Id,  
  9.                                   Title = item.Title,  
  10.                                   ReleaseYear = item.ReleaseYear,  
  11.                                   Summary = item.Summary,  
  12.                                   LastReadAt = DateTime.Now  
  13.                               })  
  14.                               .ToList();  
  15. }  

Modify the Create.cshtml.

  1. @page  
  2. @model CreateModel  
  3. @{  
  4. }  
  5.   
  6. <h2>New Movie</h2>  
  7.   
  8. <form method="post">  
  9.     <div asp-validation-summary="All"></div>  
  10.       
  11.     <label asp-for="Movie.Id"></label>  
  12.     <input asp-for="Movie.Id" /><br />  
  13.   
  14.     <label asp-for="Movie.Title"></label>  
  15.     <input asp-for="Movie.Title" />  
  16.     <span asp-validation-for="Movie.Title"></span><br />  
  17.   
  18.     <label asp-for="Movie.ReleaseYear"></label>  
  19.     <input asp-for="Movie.ReleaseYear" /><br />  
  20.   
  21.     <label asp-for="Movie.Summary"></label>  
  22.     <textarea asp-for="Movie.Summary"></textarea><br />  
  23.   
  24.     <button type="submit">Save</button>  
  25.     <a asp-page="./Index">Cancel</a>  
  26. </form>  

Modify the Create.cshtml.cs.

  1. [BindProperty]  
  2. public MovieInputModel Movie { get; set; }  
  3.   
  4. public void OnGet()  
  5. {  
  6.     this.Movie = new MovieInputModel();  
  7. }  
  8.   
  9. public IActionResult OnPost()  
  10. {  
  11.     if (!ModelState.IsValid)  
  12.         return Page();  
  13.   
  14.     var model = new Movie  
  15.     {  
  16.         Id = this.Movie.Id,  
  17.         Title = this.Movie.Title,  
  18.         ReleaseYear = this.Movie.ReleaseYear,  
  19.         Summary = this.Movie.Summary  
  20.     };  
  21.     service.AddMovie(model);  
  22.   
  23.     return RedirectToPage("./Index");  

Modify the Edit.cshtml.

  1. @page "{id:int}"  
  2. @model EditModel  
  3. @{  
  4. }  
  5.   
  6. <h2>Edit Movie - @Model.Movie.Title</h2>  
  7.   
  8. <form method="post">  
  9.     <div asp-validation-summary="All"></div>  
  10.   
  11.     <input type="hidden" asp-for="Movie.Id" />  
  12.   
  13.     <label asp-for="Movie.Title"></label>  
  14.     <input asp-for="Movie.Title" />  
  15.     <span asp-validation-for="Movie.Title"></span><br />  
  16.   
  17.     <label asp-for="Movie.ReleaseYear"></label>  
  18.     <input asp-for="Movie.ReleaseYear" /><br />  
  19.   
  20.     <label asp-for="Movie.Summary"></label>  
  21.     <textarea asp-for="Movie.Summary"></textarea><br />  
  22.   
  23.     <button type="submit">Save</button>  
  24.     <a asp-page="./Index">Cancel</a>  
  25. </form>  

Modify the Edit.cshtml.cs.

  1. [BindProperty]  
  2. public MovieInputModel Movie { get; set; }  
  3.   
  4. public IActionResult OnGet(int id)  
  5. {  
  6.     var model = this.service.GetMovie(id);  
  7.     if (model == null)  
  8.         return RedirectToPage("./Index");  
  9.   
  10.     this.Movie = new MovieInputModel  
  11.     {  
  12.         Id = model.Id,  
  13.         Title = model.Title,  
  14.         ReleaseYear = model.ReleaseYear,  
  15.         Summary = model.Summary  
  16.     };  
  17.     return Page();  
  18. }  
  19.   
  20. public IActionResult OnPost()  
  21. {  
  22.     if (!ModelState.IsValid)  
  23.         return Page();  
  24.   
  25.     var model = new Movie  
  26.     {  
  27.         Id = this.Movie.Id,  
  28.         Title = this.Movie.Title,  
  29.         ReleaseYear = this.Movie.ReleaseYear,  
  30.         Summary = this.Movie.Summary  
  31.     };  
  32.     service.UpdateMovie(model);  
  33.   
  34.     return RedirectToPage("./Index");  
  35. }  

Modify the Delete.cshtml.

  1. @page "{id:int}"  
  2. @model DeleteModel  
  3. @{  
  4. }  
  5.   
  6. <h2>Delete Movie</h2>  
  7.   
  8. <p>Are you sure you want to delete <strong>@Model.Title</strong>?</p>  
  9.   
  10. <form method="post">  
  11.     <input type="hidden" asp-for="Id" />  
  12.   
  13.     <button type="submit">Yes</button>  
  14.     <a asp-page="./Index">No</a>  
  15. </form>  

Modify the Delete.cshtml.cs.

  1. [BindProperty]  
  2. public int Id { get; set; }  
  3. public string Title { get; set; }  
  4.   
  5. public IActionResult OnGet(int id)  
  6. {  
  7.     var model = this.service.GetMovie(id);  
  8.     if (model == null)  
  9.         return RedirectToPage("./Index");  
  10.   
  11.     this.Id = model.Id;  
  12.     this.Title = model.Title;  
  13.   
  14.     return Page();  
  15. }  
  16.   
  17. public IActionResult OnPost()  
  18. {  
  19.     if (!service.MovieExists(this.Id))  
  20.         return RedirectToPage("./Index");  
  21.   
  22.     service.DeleteMovie(this.Id);  
  23.   
  24.     return RedirectToPage("./Index");  
  25. }  

Run and browse to /Movies.

ASP.NET Core

On clicking first Edit (notice the URL would be /Movies/Edit/1) -

ASP.NET Core

On clicking Delete (notice the URL would be /Movies/Delete/3) -

ASP.NET Core

Note

You could download the source code to play with it.

Discussion

Razor Pages are introduced in ASP.NET Core 2.0 to make building simple web applications quicker and are a good way to play with various ASP.NET Core concepts like Razor, Layout Pages and Tag Helpers etc.

Razor Pages use ASP.NET Core MVC under the hood however the programming model is not the same. Unlike MVC where Controllers, Models, and Views are distinct and separate components of the architecture, in Razor Pages, these concepts are brought together under one roof, Page Model.

Page Model

I like to think of Page Model as a combination of Controller and Models. Like controller because they receive the HTTP requests and like the model because they hold the data/properties for views.

For a .cshtml file to act as Page Model, it must contain as its first line the @page directive. The .cshtml.cs (code-behind) class inherits from PageModel abstract class. By convention, the code-behind class has Model appended to page’s name e.g. Index page’s code-behind is IndexModel.

Routing

Routing to pages depends on their location in your project directory structure, under the Pages folder (by default). If a page is not specified in URL, the default of Index is used.

In our sample, we navigated to URL /Movies to view the page located at /Pages/Movies/Index in our solution. Similarly, the URL /Movies/Edit maps to /Pages/Movies/Edit page.

ASP.NET Core 2.0 has introduced new constructs used for generating URLs

  • Page() method
  • asp-page Tag Helper
  • RedirectToPage() method on PageModel base class

Note that URLs starting with / are absolute paths and point to Pages folder. We can also use relative URLs stating with ./ or ../ or by simply omitting the /. To understand better, here is what happens when navigating to various URLs from Page/Movies/Delete,

Path Points to Page
/Index or ../Index Pages/Index
Index or ./Index Pages/Movies/Index
Edit or ./Edit Pages/Movies/Edit

We can specify routing constraints as part of @page directive to indicate to runtime to expect route parameters or throw 404 (Not Found) if missing.  In our Edit page we used the constraint like,

@page “{id:int}”

If you prefer to use a different name than Pages for your root folder, you could do so by configuring page options.

Handlers

As mentioned earlier, the page receives HTTP requests (i.e. acts as an Action in MVC world) and these are handled by the handler methods.  These handlers return IActionResult and named using the convention of On[verb]. Most commonly used are OnGet() and OnPost(). For asynchronous you could append Async to the name, but this is optional.

The PageModel base class has RedirectToPage() method (that returns RedirectToPageResult) to navigate to other pages and Page() method (that returns PageResult) to return the current page. Note that if return type of handler method is void, runtime returns a PageResult.

In order to have multiple handler methods for HTTP verbs, we can use named handler methods using asp-page-handler attribute. The name specified here should have a method in page class using convention On[verb][handler]. Let’s add a link to our movies list to delete the movie,

  1. <td>  
  2.     <a asp-page="./Index"   
  3.        asp-page-handler="delete"  
  4.        asp-route-id="@item.Id">Delete</a>  
  5. </td>  

Add a method in the page model class to handle this request (note its name and parameter)

  1. public IActionResult OnGetDelete(int id)  
  2. {  
  3.     if (!service.MovieExists(id))  
  4.         return RedirectToPage("./Index");  
  5.   
  6.     service.DeleteMovie(id);  
  7.   
  8.     return RedirectToPage("./Index");  
  9. }  

Move your mouse over the Delete link and you’ll notice the URL like /Movies?id=1&handler=delete. If you prefer to replace query parameters with URL segments then add following route constraints to the @page directive and generated URL will be /Movies/delete/1.

Binding

@model directive on pages points to the page model class because as mentioned earlier, this class acts as the model for Razor Pages. This works for reading the properties however in order to populate them when posting data (i.e. when using verbs other than GET) we need to use an attribute [BindProperty] to mark properties to use Model Binding.

Source Code

GitHub