代码之家  ›  专栏  ›  技术社区  ›  Mr.B

Razor页面:在导航OnGetAsync时向传递多个参数

  •  2
  • Mr.B  · 技术社区  · 7 年前

    Lists 和 Records :

    public class List
    {
        public int ID { get; set; }
    
        [StringLength(25, MinimumLength = 3, ErrorMessage = "Title should be in range between 3 and 25")]
        [Display(Name = "Title")]
    
        public string Caption { get; set; }
    
        public string UserId { get; set; }
        public User User { get; set; }
    
        public ICollection<Record> Records { get; set; }
    }
    
    public class Record
    {
        public int ID { get; set; }
        [StringLength(25, MinimumLength = 3, ErrorMessage = "Word should be in range between 3 and 25")]
        [Display(Name = "Title")]
    
        public string Word { get; set; }
        [StringLength(30, MinimumLength = 3, ErrorMessage = "Translation should be in range between 3 and 30")]
        public string Translation { get; set; }
    
        public int ListId { get; set; }
        public List List { get; set; }
    }
    

    记录 列表 . 一对多分贝: enter image description here

    我在打开 记录 从 列表 : enter image description here

    现在我想为一个 Record 看起来是这样的: enter image description here 但是,要做到这一点,我需要正确传递多个参数: ListId 和 RecordId 通过 csgtml 文件。像这样:

      <a asp-page="./Details" asp-route-id="@item.ID,@item.ListId">Details</a>
    

    方法和签名 OnGetAsync

     public async Task<IActionResult> OnGetAsync(int? id, int? listId) {...}
    

    Records/Details.cshtml

    @page "/Lists/{listId}/Records/{id}/Details/"
    

    但它不起作用!

    如果我定义 @page Records/Details.cshtml 这样地:

    @page "/Lists/{id}/Records/Details/"
    

    方法

     public async Task<IActionResult> OnGetAsync(int? id, int? listId)
    

    转到断点,但是,两个参数都为null,URL如下所示: enter image description here

    2 回复  |  直到 7 年前
        1
  •  7
  •   Kirk Larkin    7 年前

    你差不多做到了,但你需要拆分这些路由参数,并使用如下方法:

    <a asp-page="./Details" asp-route-id="@item.ID" asp-route-listId="@item.ListId">Details</a>
    

    你用 asp-route-* 要设置参数,其中*表示参数本身的名称,并用于每个单独的参数。

        2
  •  3
  •   Mike Brind    7 年前

    如果需要指定多个路由值,可以使用 asp-all-route-data 锚定标记辅助对象上的属性:

    @{   
        var routeValues = new Dictionary<string, string>
            {
               { "listId", item.ListId },
               { "id", item.ID }
            };
    }
    
    <a asp-page="./Details" asp-all-route-data="routeValues">Click</a>
    
    推荐文章