ASP.NETCore Razor Pages中的路由参数配置

admin
admin
2022-02-28
分享:

ASP.NETCore Razor Pages中的路由参数配置

导航:

在此视频中,我们将讨论在ASP.NETCore Razor Pages中路由参数。

以下是我们的ASP.NETCore项目中的Pages文件夹层次结构。

  • Index.cshtml显示所有学生的列表。
  • Details.cshmtl显示特定学生的详细信息。

学生的ID传递到Details信息 Razor Pages作为参数。考虑以下示例。我们正在将“studentId”作为参数传递给“Details”的 Razor Pages。

  <a asp-page="/Students/Details"   asp-route-ID="@student.Id" class="btn btn-primary m-1">详情</a>

默认情况下,studentId作为查询字符串参数传递,生成的代码如下所示

https://localhost:12345/students/details/1/

如果要改为将其作为路由参数传递,请使用路由模板并指定路由参数。

路由模板在.cshtml文件中使用@page指令指定。

在旁边的花括号中指定路由参数。

@page "{id}"

通过上述更改,现在将会使用StudentID作为路由参数传递。

将路径/students/details/1/关联,参考以下文件夹层次结构

默认情况下, Razor Pages的路径决定了可以访问该页面的URL,如Details.cshtml页面在Students文件夹中。而"Students"文件夹位于根路径Pages文件夹中。 因此,/students/details/ID请求在默认情况下可以访问Details.cshtml路径下的 Razor Pages。

如果要修改此设置,可以使用路由模板的覆盖功能。例如要生成

以下路由模板生成的URL:/students/details/view/1/

由于路由模板不是以/或〜/路由开头(路由模板指定的"View/{id}")将被附加到默认的根文件路径/students/details中。 我们修改Details.cshtml页面的Page命令如下:

@page "View/{id}"

生成的结果:

http://localhost:2221/students/details/view/1/

如果路由模板以/或〜/开头,则将忽略根文件路径(/students/details)。

http://localhost:2221/students/view/2/是以下路由模板生成的URL。

@page "/Students/View/{id}"

获取路由参数

将一个参数添加到OnGet()方法中,该参数的名称和数据类型与route参数相同。ASP.NETCore中的模型绑定会自动将route参数值绑定到OnGet()方法参数。

public class DetailsModel:PageModel
{
       public void OnGet(int id)
        {
            Student = _studentRepository.GetStudent(id);
        }
}

如果在视图模型中需要路由参数值,则将该值分配给公共属性。然后,可以在视图模型中使用此公共属性。




    public class DetailsModel : PageModel
{
    public int Id{get;set;}

 public void OnGet(int id)
        {
            Id=id;
        }
}

ASP.NET Core中 的 BindProperty 特性

创建一个公共属性,而不是通过方法传参的形式,将方法参数值分配给公共属性。 我们可以将BindProperty属性与SupportsGet属性设置为true一起使用。


 public class DetailsModel : PageModel
    {
        private readonly IStudentRepository _studentRepository;

        public DetailsModel(IStudentRepository studentRepository)
        {
            this._studentRepository = studentRepository;
        }

        public Student Student { get; set; }
        
        [BindProperty(SupportsGet = true)]
        public int Id { get; set; }
        /// <summary>
        /// //模型绑定自动映射查询字符串id的值,映射到OnGet()方法上的设置为id参数
        /// </summary>       
        public void OnGet()
        {
             
            Student = _studentRepository.GetStudent(Id);
        }
    }

BindProperty属性和SupportsGet属性

默认情况下,仅当请求是POST请求时,BindProperty属性才会将值绑定到PageModel类的属性。如果请求是GET请求,则不绑定值。但是,我们可以将SupportsGet属性设置为true,因此即使在GET请求中,值也将绑定到PageModel类的属性。