Section 2 of 5

Page Model Pattern

🎯 What You'll Learn

  • PageModel class
  • Properties and binding
  • BindProperty attribute
  • Dependency injection
  • Returning results

What is PageModel?

PageModel is the code-behind class for a Razor Page containing properties and handler methods.

Basic PageModel C#
public class IndexModel : PageModel
{
    public string Message { get; set; } = "Hello";

    public void OnGet()
    {
        Message = "Welcome!";
    }
}

Properties

Public properties are accessible in the view via Model.

PageModel Properties C#
public class ProductsModel : PageModel
{
    public List<Product> Products { get; set; } = new();
    public int TotalCount { get; set; }
}

BindProperty Attribute

[BindProperty] enables automatic model binding for POST requests.

Bind Property for Forms C#
public class CreateModel : PageModel
{
    [BindProperty]
    public Product Product { get; set; } = new();

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
            return Page();

        return RedirectToPage("Index");
    }
}

Dependency Injection

Inject Services C#
public class IndexModel : PageModel
{
    private readonly InvenTrackDbContext _context;

    public IndexModel(InvenTrackDbContext context)
    {
        _context = context;
    }

    public List<Product> Products { get; set; } = new();

    public async Task OnGetAsync()
    {
        Products = await _context.Products.ToListAsync();
    }
}

Returning Results

Common Return Types C#
// Return current page
return Page();

// Redirect to another page
return RedirectToPage("Index");

// Redirect with route values
return RedirectToPage("Details", new { id = 5 });

// Not Found
return NotFound();

Key Takeaways

  • PageModel: Code-behind class for Razor Pages
  • Properties: Accessible in view via Model
  • [BindProperty]: Automatic model binding
  • Dependency injection: Via constructor
  • Page(): Return current page
  • RedirectToPage(): Redirect to another page