We have a parent component and a child component :I want to raise an event from the child (on text entering), catch it in the parent and do some actions.
In child component (razor) :
<InputText class="input-field" Value="@ProductModel.ModelNumber" @oninput="HandleInputChanged" />
In Code-behind:
[Parameter] public EventCallback<string> OnModelChanged { get; set; }private async Task HandleInputChanged(ChangeEventArgs e){ var newValue = e.Value?.ToString(); ProductModel.ModelNumber = newValue; await OnModelChanged.InvokeAsync(newValue); }
In Parent Component (Razor):
<ChildFields ProductModel="ProductModel" OnModelChanged="HandleModelChanged" />
Code-Behind :
[Parameter] public ProductUpdateDto ProductModel { get; set; } = new() { ProductDiscriminator = nameof(Product) }; private void HandleModelChanged(string newValue) { Console.WriteLine($"Model changed to: {newValue}"); RefreshAutoPath(); } protected override async Task OnParametersSetAsync() { if (ProductModel != null) { ProductModel.ModelNumberChanged += RefreshAutoPath; } await base.OnParametersSetAsync(); }
In DTO also I made a change to get notified:
[StringLength(100)] public string? ModelNumber { get => _modelNumber; set { if (_modelNumber != value) { _modelNumber = value; ModelNumberChanged?.Invoke(); } } } public event Action? ModelNumberChanged;
I tried 3,4 different variations and in each got some errors.
As an example current error is:
Error: System.InvalidOperationException: Microsoft.AspNetCore.Components.Forms.InputText requires a value for the 'ValueExpression' parameter. Normally this is provided automatically when using 'bind-Value'.