Home > Back-end >  Title not rendering correctly
Title not rendering correctly

Time:01-29

This seems like it should be fairly easy, but I can't get the syntax down.

When I request /Years/1956, I want the title to render as 1956; for /Years/1957, I want to see 1957, etc.

Years.cshtml

@page "{Year:min(1956):max(2022)?}"
@model Alpha.Pages.YearsModel

@{
    ViewData["Title"] = "@Year";
}

Years.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Alpha.Pages {
    public class YearsModel : PageModel {
        public IActionResult OnGet(string Year) {
            if (@Year is null)
                return new RedirectToPageResult("Index");
            else
                return new PageResult();
        }
    }
}

CodePudding user response:

I have a suggestion like below:

  1. Inside the Razor PageModel class, set the public property Year.

      public class YearsModel : PageModel
        {
            public string Year { get; set; }
            public IActionResult OnGet(string Year)
            {
                if (@Year is null)
                    return new RedirectToPageResult("Index");
                else              
                    this.Year = Year;
                return new PageResult();
            }
        }
    
  2. Then inside the Razor HTML Page, the public property Year is accessed from the Razor PageModel class and displayed.

  @page "{Year:min(1956):max(2022)?}"
  @model Alpha.Pages.YearsModel
  
  @{
      ViewData["Title"] = @Model.Year;
  }

3.result:

enter image description here

  • Related