在我的应用程序中,我有一个用户可以提交的表单。当他们提交表单时,URL 看起来像这样:
https://localhost:5003/searchresults/q=ford&q=bronco&exclude=color:red&exclude=interior:cloth
在OnInitializedAsync
中的SearchResults.razor
上,我有这段代码:
String url = System.Net.WebUtility.UrlDecode(navigationManager.Uri);
Uri uri = navigationManager.ToAbsoluteUri(url);
Dictionary<string, StringValues> choices = QueryHelpers.ParseQuery(uri.Query);
在调试器中,我看到“选择”:
{[q, {ford,bronco}]}
{[exclude, {color:red,interior:cloth}]}
在下一页上说我要添加:
&include=option:siriusxm
&include=option:mudguards
&include=color:blue
为了让“选择”看起来像这样:
{[q, {ford,bronco}]}
{[exclude, {color:red,interior:cloth}]}
{[include, {option:siriusxm,option:mudguards,color:blue}]}
如果我这样做:
StringValues sv = new StringValues("option:siriusxm");
choices.Add("include", sv);
这会起作用。但是,如果我继续,并执行以下操作:
StringValues sv = new StringValues("option:mudguards");
choices.Add("include", sv);
我会得到错误:
ArgumentException: An item with the same key has already been added. Key: include
System.Collections.Generic.Dictionary<TKey, TValue>.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
System.Collections.Generic.Dictionary<TKey, TValue>.Add(TKey key, TValue value)
MyAwesomeApplication.Pages.SearchResults.OnInitializedAsync() in SearchResults.razor
+
choices.Add("include", sv);
我对 C#、ASP.NET 和 Blazor 相当陌生,因此我不确定如何仅向现有 StringValues
数组添加新值使用相同的 key 。
最佳答案
您的字典已有一个带有键 include
的项目,您必须将新值附加到现有的 StringValues
中:
StringValues sv = new StringValues("option:siriusxm");
sv = StringValues.Concat(sv,"option:mudguards");
或
StringValues sv = new StringValues("option:siriusxm");
choices.Add("include", sv);
choices["include"] = StringValues.Concat(choices["include"],"option:mudguards");
或者更好:
StringValues sv = new StringValues(new string[]{"option:siriusxm","option:mudguards"});
关于c# - 如何使用相同的键向 StringValues 数组添加新值,从而修改我的 Uri?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68897824/