【发布时间】:2023-01-11 08:34:13
【问题描述】:
出现错误:在线 CurrentFilters.Add($"Colors", Colors[i].ToString());
处理请求时发生未处理的异常。 ArgumentException:已添加具有相同键的项目。 关键:颜色
问题:如果
Dictionary不能拥有与我的替代方案相同的密钥?我在 Google 上发现很少有人喜欢输入List,但它们不适用于asp-all-route-data。也因为,它是自动绑定;这意味着我不能做像
CurrentFilters.Add($"Colors[i]", Colors[i].ToString());这样的事情,这会起作用,但它不会绑定Colors[1]与Colors不同。默认网址格式:
localhost234/index?Colors=red&Colors=blue&Colors=Black后端代码
[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 CurrentFilters.Clear(); CurrentFilters.Add("SearchString", SearchString); for (int i = 0; i < Colors.Count; i++) { CurrentFilters.Add($"Colors", Colors[i].ToString()); } }前端表单 - 多色下拉列表
<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>这里我在表中显示数据。标题链接用于过滤和排序。我有多个过滤器,所以我将它们添加到
asp-all-route-data。<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 中使用列表,但它给出了一个错误。
错误(活动)CS0266 无法隐式转换类型 'System.Collections.Generic.Dictionary<字符串, System.Collections.Generic.List>' 到 'System.Collections.Generic.IDictionary<string, string>'。明确的 转换存在(你错过了演员表吗?)
[BindProperty(SupportsGet = true)] public Dictionary<string, List<string>> CurrentFilters { get; set; }
【问题讨论】:
-
使用
Dictionary<string, List<string>>?或者使用asp-all-route-data以外的东西... -
你还没有提供任何关于你打算用
CurrentFilters做什么的信息。您希望CurrentFilters["Colors"]得到什么结果?它将如何使用? -
顺便说一句,为什么你有
Colors[i].ToString()?你知道Colors类型是List<string>所以Colors[i]的类型已经是string。当您不插入任何值时,为什么要执行$"Colors"? -
我尝试使用
Dictionary<string, List<string>>但它给出了相同的转换错误
标签: c# asp.net asp.net-mvc razor razor-pages