I'm using Server-side Blazor components in ASP.NET Core 3 preview 4.
I have a parent component, and child components, using the same shared model, like this :
Model :
public class CountModel
{
public int Count { get; set; }
public void Increment()
{
Count++;
}
}
Parent component :
@page "/count"
<CascadingValue Value="currentCount">
<h1>Count parent</h1>
<p>Current count is : @currentCount.Count</p>
<button class="btn btn-primary" onclick="@currentCount.Increment">+1 from parent</button>
<CountChild></CountChild>
</CascadingValue>
@functions {
private CountModel currentCount = new CountModel();
}
Child component :
<h1>Count child</h1>
<p>Current count is : @currentCount.Count</p>
<button class="btn btn-primary" onclick="@currentCount.Increment">+1 from child</button>
@functions {
[CascadingParameter]
private CountModel currentCount { get; set; }
}
It's the same instance of the model used for the parent and the child. When the model is updated from the parent, both display the correct incremented value. When it's updated from the child, only the child display the correct value.
How can I force the parent component to be refreshed when it is updated from the child ?
Note, here I have a function to update the model, but I would like the solution to work when data is bound to an input.
Create a shared service. Subscribe to the service's "RefreshRequested" event in the parent and Invoke() from the child. In the parent method call StateHasChanged();
public interface IMyService
{
event Action RefreshRequested;
void CallRequestRefresh;
}
public class MyService: IMyService
{
public event Action RefreshRequested;
public void CallRequestRefresh()
{
RefreshRequested?.Invoke();
}
}
//child component
MyService.CallRequestRefresh();
//parent component
MyService.RefreshRequested += RefreshMe;
private void RefreshMe()
{
StateHasChanged();
}