Author : MD TAREQ HASSAN | Updated : 2020/07/03

What is razor pages?

Notes:

MVC vs Razor Pages

Overview

Pages/Foo/Bar.cshtml

@page
@using Hover.Foo // the namespace where BarModel belongs
@model BarModel


<h2>Hovermind</h2>

<p>
    @Model.Message
</p>

Pages/Foo/Bar.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;

namespace Hover.Foo
{
    public class BarModel : PageModel
    {
        public string Message { get; private set; } = "Hover Now ->";

        public void OnGet()
        {
            Message += $" { DateTime.Now }";
        }
    }
}

Configuration

configurations-in-startup#razor-pages

Layout

Same as MVC: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout

Page model

Anatomy of PageModel

public class XxxModel : PageModel
{
	// bindable properties (property type => POCO i.e. public Baz baz)
	
	// DI injection properties
	
	// constructor for DI injection

	// handler methods for corresponding http verbs
}

Example: Bar.cshtml.cs

public class BarModel : PageModel
{
    [BindProperty]
    public Customer Customer { get; set; }
	
    private readonly CustomerDbContext _context;

    public BarModel(CustomerDbContext context)
    {
        _context = context;
    }

    public IActionResult OnGet()
    {
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Customers.Add(Customer);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

Handler methods

Multiple handlers

Property binding and model expression

Routing

By conmvention, path in “Pages” forlder & page file name becomes route url

To overrive default routing convention, provide absolute URL after @page directive
Example: Pages/Foo/Bar.cshtml

@page "/xxx"

<!-- ... ... ... -->

Details: https://docs.microsoft.com/en-us/aspnet/core/razor-pages/razor-pages-conventions

Route template and constraint

Pages/Foo/Bar.cshtml

@page "{id:int}"

<!-- ... ... ... -->

URL would be: “foo/bar/5

Accessing route url segments

Pages/Bar.cshtml

@page "{id:int}"

<!-- ... ... ... -->

URL: “/bar/5

Pages/Bar.cshtml.cs

public class BarModel : PageModel
{
    // ... ... ...

    public IActionResult OnGet(int id) // id = 5
    {
        // ... ... ...
    }
	
	// ... ... ...
}

ViewData

PageModel

public class AboutModel : PageModel
{
    [ViewData]
    public string Title { get; } = "About";

    public void OnGet()
    {
    }
}

Page

<h1>@Model.Title</h1>

<!-- ... ... ... -->

Layout

<!DOCTYPE html>
<html lang="en">
<head>

    <title>@ViewData["Title"] - WebApplication</title>
	
    <!-- ... ... ... -->

TempData

PageModel

[TempData]
public string Message { get; set; }

Page

<h3>Message: @Model.Message</h3>