如何将URL输入参数值传递给Blazor页面?

时间:2019-12-12 06:53:47

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

这会将值传递到blazor组件

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

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

2 个答案:

答案 0 :(得分:2)

它在文档中:components routing

答案 1 :(得分: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的公共属性并对其进行注释,则框架自动完成此操作带有Parameter属性:

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值。