I have a page that do both add and edit Commodities named CommodityAddEdit component. When we are in edit mode the Id is not null so we can figure out that we are in edit mode. In OnInitializedAsync() method I fill Model (vm) of EditForm. But after click on submit button the OnInitializedAsync() method executes too and vm fill again from database value record. How to figure out that we are filling form first time or we are in posting form mode in OnInitializedAsync() method?
<EditForm Model="@vm" OnSubmit="Submit" FormName="CommodityAddEdit"
method="post" enctype="multipart/form-data" Enhance>
[SupplyParameterFromForm]
private AddEditCommodityVm vm { get; set; } = new();
protected override async Task OnInitializedAsync()
{
if (Id is not null) // update
{
var commodity = await appDbContext.Commodities.FindAsync(Id);
if (vm.Title.Length == 0) // Load form data first time
vm = commodity!.Adapt<AddEditCommodityVm>();
}
}
public async Task Submit(EditContext editContext)
{
if (Id == null)
await Add(editContext);
else
await Update(editContext);
}
The if condition is wrong because maybe the user send empty fields.
As said in this post, you need to put on the top of your component:
@rendermode RenderMode.InteractiveAutoWith that, your OnInitializedAsync will enter only once.