本次主要来说下通过对当前URL进行,添加、更改或删除一个或多个查询参数的U R L 字符串的方法。
@page "/demoPage"
@inject NavigationManager NavigationManager
<h3>demoPage</h3>
<h2>路由查询参数:</h2>
<p>添加参数: @_newUrl</p>
<button @onclick="GetUrlQuery">更新参数</button>
@code {
private string _newUrl = string.Empty;
private void GetUrlQuery()
{
// 添加参数
_newUrl = NavigationManager.GetUriWithQueryParameter("a", "123");
}
}
上述代码中执行了NavigationManager.GetUriWithQueryParameter,为url添加了查询参数a,并设置值为123,如果设置的查询参数原本是存在的将更新原来的值,下来我们试试更新看看是否有效
@page "/demoPage"
@inject NavigationManager NavigationManager
<h3>demoPage</h3>
<h2>路由查询参数:</h2>
<p>添加参数: @_newUrl</p>
<button @onclick="GetUrlQuery">更新参数</button>
@code {
private string _newUrl = string.Empty;
private void GetUrlQuery()
{
// 添加参数
_newUrl = NavigationManager.GetUriWithQueryParameter("a", "123");
}
}
这次我们还是使用了上述的代码,和添加一样,只是这次调用时我们就传递了查询参数a=abc,可以看到如下的结果,a被更新为123,证明更新查询参数生效。
删除查询参数时我们只需要根据原有类型设置为null
@page "/demoPage"
@inject NavigationManager NavigationManager
<h3>demoPage</h3>
<h2>路由查询参数:</h2>
<p>添加参数: @_newUrl</p>
<button @onclick="GetUrlQuery">更新参数</button>
@code {
private string _newUrl = string.Empty;
private void GetUrlQuery()
{
// 添加参数
_newUrl = NavigationManager.GetUriWithQueryParameter("a", (string)null!);
}
}
我们运行后点击按钮可以看到值被正确删除了
操作多参数我们使用GetUriWithQueryParameters(),传入一个字典来更新值。 这里我们做一个这样的预期,修改a参数为123,添加b参数,删除c参数
@page "/demoPage"
@inject NavigationManager NavigationManager
<h3>demoPage</h3>
<h2>路由查询参数:</h2>
<p>添加参数: @_newUrl</p>
<button @onclick="GetUrlQuery">更新参数</button>
@code {
private string _newUrl = string.Empty;
private void GetUrlQuery()
{
// 添加参数
_newUrl = NavigationManager.GetUriWithQueryParameters(new Dictionary<string, object?>()
{
["a"] = "123",
["b"] = 18,
["c"] = null
});
}
}
运行后是与我们的预期一致
@page "/demoPage"
@inject NavigationManager NavigationManager
<h3>demoPage</h3>
<h2>路由查询参数:</h2>
<p>添加参数: @_newUrl</p>
<button @onclick="GetUrlQuery">更新参数</button>
@code {
private string _newUrl = string.Empty;
private void GetUrlQuery()
{
// 添加参数
_newUrl = NavigationManager.GetUriWithQueryParameters("https://baidu.com", new Dictionary<string, object?>()
{
["a"] = "123",
["b"] = 18,
["c"] = null
});
}
}