asp.net 字典的替代

yxyvkwin  于 2023-01-14  发布在  .NET
关注(0)|答案(1)|浏览(168)

**获取错误:**在第CurrentFilters.Add($"Colors", Colors[i].ToString());

An unhandled exception occurred while processing the request.
ArgumentException: An item with the same key has already been added. Key: Colors

**问题:**如果Dictionary不能有相同的密钥,我的替代方案是什么?我在Google上发现很少有人喜欢放入List,但他们不与asp-all-route-data一起工作。

也因为,它是自动绑定;这意味着我不能像CurrentFilters.Add($"Colors[i]", Colors[i].ToString());这样做,这将工作,但它不会绑定bc名称"Colors[1]""Colors"不同。
如果你点击<a>标签比它会发送URL格式:localhost234/Index?SearchString=text%Colors=red&Colors=blue&SortOrder=Colors_asc
后端码

[BindProperty(SupportsGet = true)]
public Dictionary<string, string> CurrentFilters { get; set; }

[BindProperty(SupportsGet = true)]
public List<string>? Colors { get; set; } //list of colors user selects
public SelectList? Colors_SELECT { get; set; } //fill dropdownlist with colors values

 public async Task OnGetAsync()
 {
     Colors_SELECT = getColors(); //fill dropdown with all colors 
    
     //this fill get back into asp-all-route-data
     CurrentFilters.Clear();
     CurrentFilters.Add("SearchString", SearchString);
     for (int i = 0; i < Colors.Count; i++)
     {
          // ISSUE is here
          CurrentFilters.Add($"Colors", Colors[i]);
     }
  }

Front-End - form对我的网格表有许多不同的过滤器

<form asp-page="./index" method="get">
     <input type="text" asp-for="SearchString" class="form-control" placeholder="Search..." />
     <select asp-for="Colors" asp-items="@Model.Colors_SELECT" class="MultiSelect" multiple>...</select>
      ...
</form>

grid-table -显示来自数据库的数据。标题链接用于过滤和排序。asp-all-route-data内部有不同的过滤器,可以传递到URL

<Table>
  ...  // header hyper link
  <a  asp-page="./Index" method="get" 
      asp-all-route-data="@Model.CurrentFilters" 
      asp-route-SortOrder="@Model.Colors_Sort" >
              @Html.DisplayNameFor(model => model.MyList[0].Colors)
     </a>
...

**更新:**我尝试在Dictionary中使用list,但它给出了一个错误。

[BindProperty(SupportsGet = true)]
public Dictionary<string, List<string>> CurrentFilters { get; set; }

错误:

Error: 'System.Collections.Generic.Dictionary<string,
 System.Collections.Generic.List<string>>' to 
'System.Collections.Generic.IDictionary<string, string>'. 
 An explicit conversion exists (are you missing a cast?)
mbskvtky

mbskvtky1#

尝试使用

[BindProperty(SupportsGet = true)]
public Dictionary<string, List<string>> CurrentFilters { get; set; }

而不是public Dictionary<string, string> CurrentFilters { get; set; }
要在OnGetAsync处理程序中处理此问题,请执行以下操作:

public async Task OnGetAsync()
{
    CurrentFilters.Clear();
    CurrentFilters.Add("SearchString", new List<string>());
    CurrentFilters["SearchString"].Add(SearchString);

    CurrentFilters.Add($"Colors", new List<string>());
    for (int i = 0; i < Colors.Count; i++)
    {
        CurrentFilters[$"Colors"].Add(Colors[i].ToString());
    }
}

相关问题