如何在组件外部放置Blazor EditForm的提交按钮 [英] How to place submit button for a Blazor EditForm outside of the component
本文介绍了如何在组件外部放置Blazor EditForm的提交按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Blazor文档的表单验证示例在EditForm
组件中具有一个提交按钮组件:
The Blazor documentation's Form Validation example has a submit button component within the EditForm
component:
<EditForm Model="@starship" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="identifier">Identifier: </label>
<InputText id="identifier" bind-Value="@starship.Identifier" />
</p>
Snip....
<button type="submit">Submit</button>
Snip...
</EditForm>
是否有将提交按钮放置在EditForm
标记之外,并且仍然使它本机"触发该EditForm
组件的提交的方式,而无需使用JavaScript?
Is there anyway to place that submit button outside of the EditForm
tags and still have it 'natively' trigger the submit for that EditForm
component without resorting to using JavaScript?
推荐答案
这很简单:
- 向
EditForm
添加 - 将提交按钮放在
EditForm
之外,并为其form
属性分配EditForm
的ID.
id
属性
- Add an
id
attribute to theEditForm
- Put the submit button outside the
EditForm
, and assign to itsform
attribute the id of theEditForm
.
这是一个工作代码示例:
Here's a working code sample:
@using System.ComponentModel.DataAnnotations;
<EditForm id="@MyID" Model="Model" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<div class="form-group">
<label for="name">Name: </label>
<InputText Id="name" Class="form-control" @bind-Value="@Model.Name">
</InputText>
<ValidationMessage For="@(() => Model.Name)" />
</div>
<div class="form-group">
<label for="body">Text: </label>
<InputTextArea Id="body" Class="form-control" @bind-Value="@Model.Text">
</InputTextArea>
<ValidationMessage For="@(() => Model.Text)" />
</div>
</EditForm>
<p>
<button type="submit" form="@MyID" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-light"
@onclick="@Cancel">Cancel</button>
</p>
@code
{
private string MyID = "myid";
private Comment Model = new Comment();
public async Task HandleValidSubmit()
{
// await Task.Delay(3000);
await Task.Run(() =>
{
Console.WriteLine("Saving...");
Console.WriteLine(Model.Name);
Console.WriteLine(Model.Text);
});
}
private void Cancel()
{
Console.WriteLine("Cancelling...");
Console.WriteLine(Model.Name);
Console.WriteLine(Model.Text);
}
public class Comment
{
[Required]
[MaxLength(10)]
public string Name { get; set; }
[Required]
public string Text { get; set; }
}
}
希望这对您有帮助...
Hope this helps...
这篇关于如何在组件外部放置Blazor EditForm的提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文