如何为现有查询字符串Blazor设置新值



我试图在不重新加载页面的情况下更改查询字符串参数。我有一个DateTimeDate值,我正试图将其转换为字符串并放入url中。说,为了这个问题,它是:

DateTime? Date = new DateTime(2020, 9, 4);

所以,我的网址可能开始看起来像:

https://localhost:44346/Events?d=2020-10-18

在我做了任何必须做的魔法之后,它最终会变成:

https://localhost:44346/Events?d=2020-10-04

我尝试过像下面这样使用NavigationManagerQueryHelpers,但没有成功:

QueryHelpers.AddQueryString(navManager.Uri, "d", Date?.ToString("yyyy-MM-dd"));

请查看此演示

@page "/counter"
@using Microsoft.AspNetCore.WebUtilities
@using System.Web 
@inject NavigationManager navManager
<button class="btn btn-primary" @onclick="ChangeUrl">Change url</button>
<br />
demonstrate lack of page reload
<br />
<button class="btn btn-primary" @onclick="AddItem">Add item</button>
@foreach (var item in list)
{
@item
}
@code {
private List<string> list = new List<string>()
{
"Test string"
};
private void AddItem()
{
var uri = navManager.ToAbsoluteUri(navManager.Uri);
if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("d", out var param))
{
list.Add(param.First());
}
else
{
list.Add("d is empty");
}
}
DateTime dateCounter = DateTime.Today;
private void ChangeUrl()
{
dateCounter = dateCounter.AddDays(1);
string url = RemoveQueryStringByKey(navManager.Uri, "d");
var query = new Dictionary<string, string> { { "d", dateCounter.ToString("dd-MM-yyyy") } };
navManager.NavigateTo(QueryHelpers.AddQueryString(url, query));
}
public static string RemoveQueryStringByKey(string url, string key)
{
var uri = new Uri(url);
// this gets all the query string key value pairs as a collection
var newQueryString = HttpUtility.ParseQueryString(uri.Query);
// this removes the key if exists
newQueryString.Remove(key);
// this gets the page path from root without QueryString
string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
return newQueryString.Count > 0
? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
: pagePathWithoutQueryString;
}
}

相关内容

  • 没有找到相关文章

最新更新