Home > Software engineering >  How to reset model in Blazor form?
How to reset model in Blazor form?

Time:05-20

In my Blazor app I have a list of items. Clicking one of the items will open a dialog component with the item as a parameter. Within the dialog is an EditForm:

<div >
    <div >
        <EditForm Model="@Item" OnValidSubmit="SaveForm">
            <p><input type="text" @bind="@Item.Title" /></p>
            <p><input type="button" @onclick="Cancel" value="Cancel" /><input type="submit" value="Save" /></p>
        </EditForm>
    </div>
</div>

@code {

    [Parameter]
    public EventCallback<Item> Callback { get; set; }

    [Parameter]
    public Item Item { get; set; } = new();
    public Item OriginalItem => Item; // <= First attempt

    protected override async Task OnInitializedAsync()
    {
        OriginalItem = Item; // <= Second attempt
    }

    async Task Cancel
    {
        Item = OriginalItem; // <= This doesn't work

        await Callback.InvokeAsync(null);
    }

    async Task SaveForm
    {
        // ...
    }
}

When I change the Item.Title value and click the Cancel-button and the dialog closes, the Item model is still updated and I see the change in the list of items. That's how Blazor works, but not what I want in this case.

I try to "reset" the Item model by keeping a copy of the original Item model parameter and overwrite it in the Cancel-function, but that doesn't seem to work.

What is the right approach?

As far as I can see the opposite happens; clicking the Cancel-button sets OriginalItem = Item. I really don't get why.

CodePudding user response:

This question is answered here Modal with Parameters still apply changes after beeing canceled

  • Related