首页 > 解决方案 > 对数组使用 asp-route-{variable} 标签助手

问题描述

我正在从这个 ASP.NET Core Razor Pages 教程中学习,我正在努力使其适应我的需求。对于分页链接,缩短为:

<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} 的说明,其中变量(代码段中的 currentFilter)是一个数组。就我而言,在我看来,我已将 CurrentFilter 调整为具有 multiple 属性的选择框,它在 URL 中显示如下:

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

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

标签: c#asp.net-corerazor-pages

解决方案


The hacky feeling workaround I'm doing until I get a great answer...

I've updated my CSHTML to have use 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>

then I reconstruct CurrentFilter if I have CurrentFilterN and no CurrentFilter in my OnGet method.

        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();
        }

So if the user uses the multiselect, CurrentFilter gets set properly. If they hit next, SearchString0, SearchString1, ..., SearchStringN get passed through in the query string which gets parsed out into CurrentFilter.

Feels hacky, but works.


推荐阅读