I tried to pass an interger id value from a parent page to a component named TestComponent, the passed id only can be shown on htmal area but always show 0 in the page OnInitializedAsync() event.
1 Parent page
<div >
<TestComponent @ref="_windowComp" id="@warehouseShipment.ShipId" />
<button @onclick="@(()=> _windowComp.Show())" class="btn btn-success btn-label btn-sm waves-effect waves-light "
<i class="ri-briefcase-5-line label-icon align-middle fs-16 me-2"></i>Reserve Inventory</button>
</div>
2 Test Component
<h3>TestComponent</h3>
<TelerikWindow @bind-Visible="@_visible" Centered="true">
<WindowTitle>
Reserve Inventory
</WindowTitle>
<WindowContent>
<p>@(test + id.ToString())</p>
</WindowContent>
<WindowActions>
<WindowAction Name="Close" />
<WindowAction Name="Maximize" />
<WindowAction Name="Minimize" />
</WindowActions>
</TelerikWindow>
@code {
[Parameter]
public int id { get; set; }
private string test = "";
private bool _visible;
public void Show()
{
_visible = !_visible;
StateHasChanged();
}
protected override async Task OnInitializedAsync()
{
if (id == 0)
test = "Fail";
else
test = "Success";
}
}`
3 Result If I pass a id value 3 , on the TestComponent, always show Fail3 which means the html part can read the id value 3 but in the OnInitializedAsync(), id is 0. I want to read the id value inside OnInitializedAsync() so that I can used the id to read database record. Thanks
The basic concept works - it's fundamental to components. See my code below.
Your problem is almost certainly in the order that events occur.
I'm guessing that you are getting warehouseShipment
in async code in the parent component, probably in OnInitializedAsync
. In which case the component is rendered when the async code yields (and warehouseShipment.ShipId
is at it's default value of 0). You need to change to using OnParametersSetAsync
which is called every time the component renders.
Here's a stripped down simple version of your component that demonstrates the problem and how to resolve it.
<div class="bg-dark text-white m-2 p-1">
<pre>Value : @this.id</pre>
<pre>Internal Value 1 : @_id1</pre>
<pre>Internal Value 2 : @_id2</pre>
</div>
@code {
[Parameter] public int id { get; set; }
private int _id1;
private int _id2;
protected override Task OnInitializedAsync()
{
_id1 = this.id;
return Task.CompletedTask;
}
protected override Task OnParametersSetAsync()
{
if (_id2 != id)
{
_id2 = this.id;
//do you stuff
}
return Task.CompletedTask;
}
}
And a Demo page:
@page "/"
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<IdComponent id=_id />
<button class="btn btn-primary" @onclick=this.Increment>Increment</button>
@code {
private int _id = 0;
private void Increment()
=> _id++;
protected override async Task OnInitializedAsync()
{
// pretend to do some async work like fetching data from a database
await Task.Yield();
_id = 4;
}
}