In a Blazor form, I'd like to be able to detect whenever a form value has changed, and set a boolean value as a result.
Here is some code to illustrate how I am currently doing it:
<EditForm Model="Person" OnValidSubmit="OnSubmitValidateForm">
<div class="form-group">
<label>First Name</label>
<input type="text" value="@Person.FirstName" @onchange="OnFirstNameChanged" />
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" value="@Person.Surname" @onchange="OnSurnameChanged" />
</div>
<input type="submit" class="btn btn-primary" value="Save"/>
</EditForm>
@code {
Person Person = new Person();
bool dataChanged = false;
void OnFirstNameChanged(ChangeEventArgs e)
{
Person.FirstName = e.Value.ToString();
dataChanged = true;
StateHasChanged();
}
void OnSurnameChanged(ChangeEventArgs e)
{
Person.Surname = e.Value.ToString();
dataChanged = true;
StateHasChanged();
}
}
In the above form I have two fields - "FirstName" and "Surname" which are properties of the "Person" class. There is an input textbox bound to each property. Whenever the value changes in either textbox, the respective method is called which will update the property value, and also indicate that the form data has changed.
It seems excessive to have an event handler for every form item, when in each case all it's really doing is what @bind="" would do, plus setting dataChanged to true.
My question is, whilst the approach works, it seems like I have to write quite a lot of extra code. Is there a better way to handle this?