How does the EditForm for Blazor handle the state of the model passed to it?

821 Views Asked by At

So, i have a blazor EditForm and i pass a model to it.

Lets suppose i have a Person class with an Id a Name and an Age

public class Person{

    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}

i create an instance (Dummy) of a Person and pass it to an EditForm

<EditForm Model="Dummy" OnValidSubmit="HandleValidSubmit">
...
</EditForm>

@code{
    private void HandleValidSubmit()
    {
        //handle form submit
    }
}

so, i suppose the EditForm isnt directly modifying the original instance of the class (Dummy) because it needs to be validated first, so all the submitting logic of the (i suppose copy) of the object needs to be written by me on the HandleSubmit method, or am i missing something?

in this case how do i actually confirm the edits on the original model on the HandleSubmit method? i cant just do Dummy(Original) = Dummy(???)

2

There are 2 best solutions below

1
On BEST ANSWER

Before the form validates the data, the handler stores all the data mapping the inputs with your model, so you just call for example:

private void HandleValidSubmit()
{
    var user = _userService.GetByName(Dummy.Name)
}

or simply you can use Dummy in any place, it has the data from the Form mapped

1
On

It updates model you passed to it. But do not any validation by itself except for numbers and datetime which do some parsing validation. To do validation you should use for example DataAnnotationValidator component and Data Annotation Validation Attributes in class definition. When you insert data model object updated and when you press submit button it first check validation state by calling EditContext.Validate and then if it return true call the OnValidSubmit. To be precise it do following:

private async Task HandleSubmitAsync()
{
    Debug.Assert(_editContext != null);

    if (OnSubmit.HasDelegate)
    {
        // When using OnSubmit, the developer takes control of the validation lifecycle
        await OnSubmit.InvokeAsync(_editContext);
    }
    else
    {
        // Otherwise, the system implicitly runs validation on form submission
        var isValid = _editContext.Validate(); // This will likely become ValidateAsync later

        if (isValid && OnValidSubmit.HasDelegate)
        {
            await OnValidSubmit.InvokeAsync(_editContext);
        }

        if (!isValid && OnInvalidSubmit.HasDelegate)
        {
            await OnInvalidSubmit.InvokeAsync(_editContext);
        }
    }
}

As you may know .NET Core is an Open Source Project and you can see the source of it here: EditForm Component