在Blazor WASM客户端应用程序中无法从验证正常工作。
将InputText元素封装到组件以紧凑布局将不再执行验证,否则该验证将正确执行。
使用类似的模型
public class Customer {
[Required]
[StringLength(100)
public string customerName {get; set;} = "";
}
以
的形式<EditForm Model=@customer>
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-row">
<div class="form-group mb-0 col-sm-12">
<div class="input-group input-group-sm mb-1 mt-1">
<div class="input-group-prepend">
<span class="input-group-text" style="width:6em;">Firma</span>
</div>
<InputText type="text" class="form-control" @bind-Value=customer.customerName />
</div>
</div>
</EditForm>
验证正常!
但是要模块化,我将内部内容外包给一个单独的组件
@page "/inputGroup"
<div class="input-group input-group-sm mb-1 mt-1">
<div class="input-group-prepend">
<span class="input-group-text" style="width:6em;">@label</span>
</div>
<InputText type=@type class="form-control" @bind-Value=@data @oninput=@onChange />
</div>
@code {
[Parameter]
public string label {get; set;} = "Label:";
[Parameter]
public string type {get; set;} = "text";
[Parameter]
public string data {get; set;} = "";
[Parameter]
public EventCallback<string> dataChanged {get; set;}
private Task onChange(ChangeEventArgs e) {
data = (string)e.Value;
return dataChanged.InvokeAsync(data);
}
}
然后我将其放入表单,例如
...
<div class="form-row">
<div class="form-group mb-0 col-sm-12">
<InputGroup label="Firma:" @bind-data=customer.customerName />
</div>
</div>
...
验证不起作用!?
答案 0 :(得分:0)
您可以在子类化 InputText
InputTextGroup.razor
@inherits Microsoft.AspNetCore.Components.Forms.InputText
<div class="mt-1">
<input type="text" id="@Id"
@attributes="@AdditionalAttributes" @bind="@CurrentValueAsString"
class="@CssClass myOtherCssClasses" />
</div>
@if (ValidationFor != null)
{
<div class="myValidationClass">
<ValidationMessage For="ValidationFor" />
</div>
}
还有InputTextGroup.razor.cs
public partial class InputTextGroup
{
[Parameter] public string Id { get; set; } = HeadlessUI.HtmlElement.GenerateId();
[Parameter] public string? Label { get; set; }
[Parameter] public Expression<Func<string>>? ValidationFor { get; set; }
}
我从这个SO answer和这个Microsoft docs中获得灵感