'How to reset model in Blazor form?
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 class="modal-container">
<div class="modal">
<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.
Solution 1:[1]
I assume your dialog is inside a Component which is passed a Parameter of type Item? Anyway, I had the same issue as you and solved it quite easily.
Give your dialog component local properties.
Public string Title {get;set;}
In OnInitializedAsync, set your local properies to the value of your Item properties
this.Title = Item.Title
Bind the Input field of the dialog to its local properties instead of Item properties.
<Input @bind=Title>
When you hit cancel just do nothing. Only close the dialog.
When you hit Save, set the Item properties to the value of local properties
Item.Title = Title
The should do the trick
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gilles Radrizzi |
