Blazor-处理URL中查询参数

本次主要来说下通过对当前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
        });
    }
}

在这里插入图片描述

运行后是与我们的预期一致

使用非当前的url

@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
        });
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code-Study

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值