我有一个EditForm,它包含一个用于打开弹出窗口的按钮。我发现,只要我点击按钮,就会调用OnValidSubmit中指定的函数。
只有当打开弹出窗口的按钮放在窗体内部时才会发生这种情况。如果我把它放在外部,函数就不会被调用。
只有当我单击提交按钮时,才能调用OnValidSubmit中指定的函数。
这是一个精简的测试页面:
@page "/testpage"
<h3>Test Page</h3>
<EditForm Model="mdl" OnValidSubmit="Save">
<div class="form-container" style="border:1px solid 0">
<FluentValidationValidator />
<ValidationSummary />
<InputText @bind-Value="mdl.Prop1"></InputText>
<button @onclick="OpenPopup">Open popup (within form)</button>
</div>
<button type="submit">Save</button>
</EditForm>
<button @onclick="OpenPopup">Open popup (outside form)</button>
<TestDialog @bind-Visible="isDlgVisible" OnDlgClosed="OnDialogClose" OnDlgSetValue="OnDialogSetValue"></TestDialog>
@code {
private MyModel mdl = new();
private bool isDlgVisible = false;
private void OpenPopup()
{
isDlgVisible = true;
}
private void OnDialogSetValue(string v)
{
// ... Here I will use the value selected through the popup ...
}
private void OnDialogClose()
{
isDlgVisible = false;
}
private void Save()
{
// This function is called as soon as I click on the "Open popup (within form)" button.
Console.WriteLine("Save!");
}
class MyModel
{
public string Prop1 { get; set; }
}
}
这是弹出组件:
<SfDialog IsModal="true" Width="200px" ShowCloseIcon="true" @bind-Visible="Visible" CssClass="mydialog">
<DialogEvents Closed="OnDlgClosed"></DialogEvents>
<DialogTemplates>
<Header>Test Popup</Header>
<Content>
<button @onclick="SetAndClose">Set and close</button>
</Content>
</DialogTemplates>
</SfDialog>
@code {
[Parameter] public bool Visible { get; set; }
[Parameter] public EventCallback<CloseEventArgs> OnDlgClosed { get; set; }
[Parameter] public Action<string> OnDlgSetValue { get; set; }
// Blazor gives an error if I don't declare this property, even if it's not used anywhere...
[Parameter] public EventCallback<bool> VisibleChanged { get; set; }
private void SetAndClose()
{
if (OnDlgSetValue != null)
{
OnDlgSetValue.Invoke("Set through popup.");
}
Visible = false;
}
}
将type="button"
添加到打开模式的按钮:
<button type="button" @onclick="OpenPopup">Open popup (within form)</button>
这是因为当未指定type
属性时,表单内按钮的默认值为submit
。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-型
如果不起作用,您可以将@onclick:preventDefault
添加到按钮中以阻止表单提交:
<button @onclick="OpenPopup" @onclick:preventDefault>Open popup (within form)</button>
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling?view=aspnetcore-6.0#防止默认操作