当自定义子组件更改状态时,Blazor EditForm DataAnnotationsValidator 意外验证
Blazor EditForm DataAnnotationsValidator validates unexpectedly when a custom child component changes state
我的 EditForm
和 DataAnnotationsValidator
包含一个可以修改其自身状态的自定义组件。下面的简单代码提供了一个重现。
单击 MyComponent 中的按钮时,将在表单上触发验证。即使 none 个表单字段已被修改,也会发生这种情况,这是意外和不希望的。
这是预期的行为吗?如果是这样,我怎样才能避免通过更改子组件触发验证?
这发生在 Blazor 服务器项目中 运行 .NET 6.0.3。
Index.razor
@page "/"
@using System.ComponentModel.DataAnnotations
<EditForm Model="model">
<DataAnnotationsValidator />
<ValidationSummary />
<label>
Name:
<InputText @bind-Value="model.Name" />
</label>
<MyComponent />
</EditForm>
@code {
MyModel model = new();
class MyModel
{
[Required]
public string? Name { get; set; }
}
}
MyComponent.razor
<p>
MyComponent: @(Switch ? "ON" : "OFF")
<button @onclick="() => Switch = !Switch">Toggle</button>
</p>
@code {
bool Switch = false;
}
在您的 MyComponent
中,将类型设置为 button
:
<button type="button" @onclick="() => Switch = !Switch">Toggle</button>
对于大多数(您可以将其解释为几乎“所有”的意思)浏览器,默认的按钮类型是 submit
。在 Blazor 中,当 提交 表单时会触发验证,换句话说,当单击 EditForm
中类型为 submit
的按钮时。这就是为什么您需要将类型设置为 button
.
我建议阅读 the following article 有关按钮上 type
属性的更多背景知识。
我的 EditForm
和 DataAnnotationsValidator
包含一个可以修改其自身状态的自定义组件。下面的简单代码提供了一个重现。
单击 MyComponent 中的按钮时,将在表单上触发验证。即使 none 个表单字段已被修改,也会发生这种情况,这是意外和不希望的。
这是预期的行为吗?如果是这样,我怎样才能避免通过更改子组件触发验证?
这发生在 Blazor 服务器项目中 运行 .NET 6.0.3。
Index.razor
@page "/"
@using System.ComponentModel.DataAnnotations
<EditForm Model="model">
<DataAnnotationsValidator />
<ValidationSummary />
<label>
Name:
<InputText @bind-Value="model.Name" />
</label>
<MyComponent />
</EditForm>
@code {
MyModel model = new();
class MyModel
{
[Required]
public string? Name { get; set; }
}
}
MyComponent.razor
<p>
MyComponent: @(Switch ? "ON" : "OFF")
<button @onclick="() => Switch = !Switch">Toggle</button>
</p>
@code {
bool Switch = false;
}
在您的 MyComponent
中,将类型设置为 button
:
<button type="button" @onclick="() => Switch = !Switch">Toggle</button>
对于大多数(您可以将其解释为几乎“所有”的意思)浏览器,默认的按钮类型是 submit
。在 Blazor 中,当 提交 表单时会触发验证,换句话说,当单击 EditForm
中类型为 submit
的按钮时。这就是为什么您需要将类型设置为 button
.
我建议阅读 the following article 有关按钮上 type
属性的更多背景知识。