这是一个有效的单页组件,它演示了实现表单提交所需的代码<CTL>S
。为了简单起见,我使用了DataAnnotationsValidator
。有内联注释来解释这些方法。
@page "/"
@implements IDisposable
@using Toolbelt.Blazor.HotKeys
@using System.ComponentModel.DataAnnotations;
<h3>EditForm</h3>
<EditForm EditContext="this._editContext" OnValidSubmit="ValidSubmitForm" OnInvalidSubmit="InvalidSubmitForm">
<DataAnnotationsValidator />
<div class="p-2">
<span>Value (100-200):</span>
<InputNumber @bind-Value="_model.Value" />
<ValidationMessage For="() => _model.Value"/>
</div>
<div class="m-2 p-2">
<button class="btn btn-success" type="submit">Submit</button>
</div>
</EditForm>
<div class="m-2 p-2">
<span>@message</span>
</div>
<div class="m-2 p-2">
<button class="btn btn-danger" type="button" @onclick="SubmitFormExternally">Submit Form Externally</button>
</div>
@code {
private string message;
private Model _model = new Model();
[Inject] private HotKeys hotKeys { get; set; }
private HotKeysContext _hotKeysContext;
EditContext _editContext;
// Explicitly setup the Edit context so we have a reference to it
protected override void OnInitialized()
{
_editContext = new EditContext(_model);
_hotKeysContext = this.hotKeys.CreateContext()
.Add(ModKeys.Ctrl, Keys.S, SubmitFormCtlS, "Submit form");
}
// Invalid handler
private Task ValidSubmitForm()
{
message = $"Valid Form Submitted at :{DateTime.Now.ToLongTimeString()}";
return Task.CompletedTask;
}
// Valid Handler
private Task InvalidSubmitForm()
{
message = $" Invalid Form Submitted at :{DateTime.Now.ToLongTimeString()}";
return Task.CompletedTask;
}
// Method to call from external button
// Works and component updates as it's a Blazor Component event
// emulates the private HandleSubmitAsync method in EditForm
private async Task SubmitFormExternally()
{
if (_editContext.Validate())
await this.ValidSubmitForm();
else
await this.InvalidSubmitForm();
}
// Method to call from shortcut key
// The shortcut key mechanism does't wrap the call in a Blazor Component event
// So we wrap the code within one
// The code emulates the private HandleSubmitAsync method in EditForm
private async Task SubmitFormCtlS()
{
var task = Task.CompletedTask;
if (_editContext.Validate())
task = this.ValidSubmitForm();
else
task = this.InvalidSubmitForm();
this.StateHasChanged();
if (!task.IsCompleted || task.IsCanceled)
{
await task;
this.StateHasChanged();
}
}
public void Dispose()
{
_hotKeysContext.Dispose();
}
// Quick Model Class
public class Model
{
[Range(100, 200, ErrorMessage = "Must be between 100 and 200")]
public int Value { get; set; } = 0;
}
}