【发布时间】:2020-11-10 19:50:02
【问题描述】:
我正在尝试让 Required 属性与 InputSelect 一起使用,但验证在 Blazor Server 中不起作用。无需选择即可提交表单。有趣的是,它在模型属性可以为空时起作用。在 .NET 5.0 之前,它不适用于可空类型,因为 InputSelect 不支持它们。然而,我想要一个不可为空的必需属性,因为我想将我的 API 中的 dto 作为模型重用,而且它在逻辑上是错误的。
public class SomeModel
{
[Required]
public string SomeString { get; set; }
[Required]
public SomeEnum SomeEnum { get; set; }
[Required]
public SomeEnum? SomeNullableEnum { get; set; }
[Required]
public int SomeInt { get; set; }
[Required]
public int? SomeNullableInt { get; set; }
}
public enum SomeEnum
{
A = 1,
B = 2
}
页面
@page "/testrequired"
@using TestNET5BlazorServerApp.Data;
<EditForm Model="Model" OnValidSubmit="Submit">
<DataAnnotationsValidator />
<ValidationSummary />
String:
<br />
<InputText @bind-Value="Model.SomeString" />
<br />
<br />
Enum:
<br />
<InputSelect @bind-Value="Model.SomeEnum">
<option value="">Select Enum</option>
<option value="@SomeEnum.A">@SomeEnum.A</option>
<option value="@SomeEnum.B">@SomeEnum.B</option>
</InputSelect>
<br />
<br />
Nullable Enum:
<br />
<InputSelect @bind-Value="Model.SomeNullableEnum">
<option>Select Nullable Enum</option>
<option value="@SomeEnum.A">@SomeEnum.A</option>
<option value="@SomeEnum.B">@SomeEnum.B</option>
</InputSelect>
<br />
<br />
Int:
<br />
<InputSelect @bind-Value="Model.SomeInt">
<option>Select Int</option>
<option value="1">1</option>
<option value="2">2</option>
</InputSelect>
<br />
<br />
Nullable Int:
<br />
<InputSelect @bind-Value="Model.SomeNullableInt">
<option>Select Nullable Int</option>
<option value="1">1</option>
<option value="2">2</option>
</InputSelect>
<br />
<br />
<button type="submit">Save</button>
</EditForm>
@code
{
SomeModel Model = new Data.SomeModel();
void Submit()
{
System.Diagnostics.Debug.WriteLine("Enum " + Model.SomeEnum);
System.Diagnostics.Debug.WriteLine("Nullable Enum " + Model.SomeNullableEnum);
System.Diagnostics.Debug.WriteLine("Int " + Model.SomeInt);
System.Diagnostics.Debug.WriteLine("Nullable Int " + Model.SomeNullableInt);
}
}
【问题讨论】:
标签: c# asp.net blazor blazor-server-side