This is probably a simple goof, but can't figure it out.
I have a Blazor form with a few input controls mapped to an object (FormFieldsModel
) mapped to an edit context. I have an Add
button that uses those fields to add the data to a grid that uses a collection of those objects. Then another Submit
button to send the whole collection to the API.
The desired flow would be, any time the user presses Add
, validation is run against the edit context form fields. If they are invalid, display any messages. If it is valid, add the item to the collection (see OnAddClicked
), and reset the form, but retaining the SubmitterInitials data (see ClearInput
). They can then either submit the collection of items, or add another item.
What is happening is, if there are no items yet added to the collection, my Validation works correctly if the user presses Add
. If they enter the data correctly, the item is added to the list, a new form object is created, but validation messages display.
<div>
<EditForm EditContext="@editContext">
<DataAnnotationsValidator />
<ValidationSummary />
....
</EditForm>
....
@code{
ObservableCollection<FormFieldsModel> items;
FormFieldsModel? formFields;
EditContext exitContext;
protected override async Task OnInitializedAsync()
{
formFields = new FormFieldsModel();
editContext = new EditContext(formFields);
validationMessageStore = new(editContext);
}
public void OnAddClicked()
{
validationMessageStore.Clear();
if (!editContext.Validate()) return;
items.Add(formFields);
ClearInput();
}
public void ClearInput()
{
formFields = new FormFieldsModel
{
// I want this to persist for any additional records
SubmitterInitials = formFields.SubmitterInitials
};
editContext = new EditContext(formFields);
validationMessageStore.Clear();
editContext.NotifyValidationStateChanged();
}
public class FormFieldsModel
{
public string ItemNumber {get; set;}
public int Quantity {get; set;
public string SubmitterInitials {get; set;}
}
}