我刚刚开始学习如何使用Blazor模板制作网站。但是我不知道如何将数据从一页传递到另一页。它与.NET CORE MVC Web应用程序略有不同,我找不到为此的示例。
<p>Solve This problem: @rnd1 * @rnd2 = ?</p>
<input type="text" name="result" bind="@result" />
<input type="button" onclick="@calculate" value="Submit" />
我想将文本框中的值发送到另一个页面。我该怎么办?
答案 0 :(得分:6)
您可以将其作为参数传递。
在要导航至的页面中,将参数添加到您的路线中:
@page "/navigatetopage/{myvalue}"
并确保该参数存在于该页面中:
[Parameter]
private string myvalue{ get; set; }
在同一页面上,您可以在以下位置进行选择:`
protected override void OnParametersSet()
{
//the param will be set now
var test = myvalue;
}
现在,请确保在起始页中导航至第二页,其中包括以下值:
uriHelper.NavigateTo($"/navigatetopage/{result}");
需要这样注入uriHelper:
@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper uriHelper
答案 1 :(得分:1)
我个人更喜欢在 url 中添加查询字符串。
例如当我想在页面加载时预选标签时:
像http://localhost:5000/profile?TabIndex=2
一样调用网址
在您的代码中,您可以使用 NavigationManager 和 QueryHelpers
添加using Microsoft.AspNetCore.WebUtilities;
然后覆盖生命周期方法之一并解析查询参数
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
Uri uri = this.Nav.ToAbsoluteUri(this.Nav.Uri);
if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("TabIndex", out StringValues values))
{
if (values.SafeAny())
{
_ = int.TryParse(values.First(), out int index);
this.TabIndex = index;
}
}
}
}