【问题标题】:Using asp-route-{variable} tag helper for an array对数组使用 asp-route-{variable} 标签助手
【发布时间】:2019-06-16 09:56:11
【问题描述】:

我正在向 this ASP.NET Core Razor Pages tutorial 学习,我正在努力使其适应我的需求。对于分页链接,缩短为:

<a asp-page="./Index"
   asp-route-pageIndex="@(Model.Student.PageIndex + 1)"
   asp-route-currentFilter="@Model.CurrentFilter"
   class="btn btn-default">
    Next
</a>

我找不到如何处理 asp-route-{variable} 的说明,其中变量(sn-p 中的 currentFilter)是一个数组。就我而言,在我看来,我已将 CurrentFilter 调整为具有多个属性的选择框,它在 URL 中显示如下:

https://localhost/Student/?currentFilter=foo&currentFilter=bar

它以字符串数组的形式进入我的模型。我找不到任何关于如何使用 asp-route 标签助手将数组传递到查询字符串的文档或解决方案。

【问题讨论】:

    标签: c# asp.net-core razor-pages


    【解决方案1】:

    在我得到一个很好的答案之前,我正在做的 hacky 感觉解决方法......

    我已更新我的 CSHTML 以使用 asp-all-route-data。

    @{
        var nextParms = new Dictionary<string, string>();
    
        int x = 0;
        nextParms.Add("pageIndex", (Model.Mini.PageIndex + 1).ToString());
        foreach (string item in Model.CurrentFilter)
        {
            nextParms.Add("SearchString" + x, item);
            x++;
        }
    }
    
    <a asp-page="./Index"
       asp-all-route-data="nextParms"
       class="btn btn-default">
        Next
    </a>
    

    如果我的 OnGet 方法中有 CurrentFilterN 并且没有 CurrentFilter,我将重建 CurrentFilter。

            if (CurrentFilter !=null && CurrentFilter .Count()>0)
            {
                //Logic if CurrentFilter exists as normal
            }
            else
            {
               List<string> SearchList = new List<string>();
    
                foreach (var key in HttpContext.Request.Query)
                {
                    if (key.Key.Contains("SearchString"))
                    {
                        SearchList.Add(key.Value);
                        string IndividualTag = key.Value;
                    }
                    //Same logic as above
                }
    
                CurrentFilter = SearchList.ToArray();
            }
    

    因此,如果用户使用多选,则 CurrentFilter 会正确设置。如果他们点击下一个,SearchString0、SearchString1、...、SearchStringN 将在查询字符串中传递,该查询字符串被解析为 CurrentFilter。

    感觉很老套,但很管用。

    【讨论】:

      【解决方案2】:

      我最终将值放入以逗号分隔的字符串,然后使用string.Split(',').Select(s=&gt;int.Parse(s))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-03
        • 1970-01-01
        • 2019-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-25
        • 2019-01-03
        相关资源
        最近更新 更多