出现错误:在线
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]);
}
}
前端 - 表单对于我的网格表有许多不同的过滤器
<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>
...
更新:我尝试在字典中使用列表,但它给出了错误。
[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?)
尝试使用
[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());
}
}