【问题标题】:How to pass a URL input parameter value to Blazor page?如何将 URL 输入参数值传递给 Blazor 页面?
【发布时间】:2020-04-05 12:38:27
【问题描述】:

这会将值传递给 blazor 组件

[Parameter]
public string Id { get; set; }

但是从 URL 输入参数传递一个值呢?

【问题讨论】:

  • 添加@page "/path/to/page/{id:string}" ?
  • 尝试等待 Http.PutJsonAsync($"/path/to/page/{Id}, value);

标签: c# asp.net asp.net-core blazor


【解决方案1】:

在组件中定义并使用 Parameter 属性注释的公共属性用于存储从父组件传递给子组件的 Component 参数,例如,以下代码从父组件传递字符串参数组件到它的子组件。

ParentComponent.razor

<ChildComponent Title="I'm a child component" />

ChildComponent.razor

<p>@Title</p>

@code{
     Public string Title { get; set; } = "Default Title";
}

或者,存储路由数据的值,例如,路由数据 Start 位于 url https://localhost:44396/counter/123 中,如果您定义了一个名为 Start 的公共属性,并使用参数属性:

Counter.razor

    @page "/counter"
@page "/counter/{start:int}"

<h1>Counter</h1>

<p>Current count: @Start</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {

    [Parameter]
    public int Start { get; set; }


    private void IncrementCount()
    {
        Start++;
    }
}

注意,Counter 组件的定义包含两个路由模板。第一个路由模板设置为使用 Start 属性的默认值;即值 0。但用户可以通过在 url 中提供路由参数来更改默认值,例如:https://localhost:44396/counter/123。现在当按钮被点击时,起始值是 123,而不是 0。为了记录,第二个模板包含一个路由约束,它将应用程序限制为只能使用 int 值。

【讨论】:

    【解决方案2】:

    在文档中:components routing

    【讨论】:

    • 路由在 mainlayout 中不起作用? :) 仅在 razor 组件中!
    • @001 - 如果这是问题所在,那么您需要提出一个更好的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多