Multiple submit buttons in Blazor EditForm?
Ok, I ended up with the following solution. It seems to work as expected.
<EditForm Model="@selectedCar" Context="formContext">
<DataAnnotationsValidator />
<ValidationSummary />
....My <InputText>'s for all values I have in my object
<button type="submit" class="btn btn-primary" @onclick="@(() => SaveCar(formContext))">Save</button>
<button type="submit" class="btn btn-primary" @onclick="@(() => UpdateStockQuantity(formContext))">Update stock quantity</button>
<button type="submit" class="btn btn-secondary" @onclick="@(() => DeleteCar(formContext))">Delete</button>
</EditForm>
@code {
[Parameter]
public string Id { get; set; }
CarModel selectedCar;
protected override async Task OnInitializedAsync()
{
selectedCar = await _CarService.GetCar(int.Parse(Id));
}
protected async Task SaveCar(EditContext formContext)
{
bool formIsValid = formContext.Validate();
if (formIsValid == false)
return;
selectedCar.Id = await _CarService.SaveCar(selectedCar);
}
... plus same approach with UpdateStockQuantity and DeleteCar.
}
The two buttons will submit the form with the validations.
And then you can check on the Boolean and call any logic you want:
<EditForm Model="@Input" OnValidSubmit="@UpdateAsync">
<DataAnnotationsValidator />
<div class="row">
<div class="form-group col-md-12">
<label class="required"> Name</label>
<InputText class="form-control" @bind-Value="Input.Name" />
<span class="err"><ValidationMessage For="@(() => Input.Name)" /></span>
</div>
</div>
<div class="text-center">
<button type="submit" @onclick="@(()=> Input.IsNew = false)" class="btn">save 1</button>
<button type="submit" @onclick="@(()=> Input.IsNew = true)" class="btn">save 2</button>
</div>
</EditForm>
@code{
async Task UpdateAsync()
{
if (Input.IsNew)
{
//do somthing
}
else
{
//do another somthing
}
}
}
If you use type="button"
then only the @onclick
method is called and not the OnValidSubmit
method. But this way there's no validation.