به صورت پیش فرض یک EditForm تنها یک دکمهی submit دارد و معمولا برای اعتبارسنجی فرم، قبل از ارسال اطلاعات به شکل زیر از آن استفاده میشود:
<EditForm Model="@selectedCar" OnValidSubmit="@SaveObject">
<DataAnnotationsValidator />
<ValidationSummary />
....My <InputText>'s for all values I have in my object
<button type="submit" value="Save">Save</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 SaveObject()
{
selectedCar.Id = await _CarService.SaveCar(selectedCar);
}
}
حال اگر بخواهیم از چند دکمه با عملکردهای مختلفی در یک EditForm استفاده کنیم چه؟ آیا امکان آن وجود دارد که برای یک دکمه اعتبارسنجی صورت پذیرد، اما برای دکمهی دیگری در همان EditForm هیچ اعتبارسنجی اعمال نشود؟
پاسخ: بله؛ میتوان به شکل زیر عمل نمود:
<EditForm Model="@selectedCar" Context="formContext">
<DataAnnotationsValidator />
<ValidationSummary />
....My <InputText>'s for all values I have in my object
<button type="submit" @onclick="@(() => SaveCar(formContext))">Save</button>
<button type="submit" @onclick="@(() => UpdateStockQuantity(formContext))">Update stock quantity</button>
<button type="submit" @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);
}
protected async Task DeleteObject(EditContext formContext)
{
selectedCar.Id = await _CarService.DeleteCar(selectedCar);
}
// ... plus same approach with UpdateStockQuantity.
}
در اینجا به جای OnValidSubmit، از Context استفاده میکنیم و توسط Anonymous Function ها، متدهای مربوط به onclickها را صدا میزنیم و formContext را به آنها منتقل مینماییم. برای اعتبارسنجی نیز در متد مربوطه با استفاده از Context.Validate اعتبار فرم را برای متد مربوطه چک میکنیم. قاعدتا نیازی نیست موقع حذف یک خودرو، اعتبارسنجی فرم، برای نام آن خودرو انجام گردد؛ اما برای ثبت یک خودرو ممکن است بخواهیم مطمئن شویم که حتما نامی برای آن اختیار شود.