我在 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>
...
验证不起作用!?
你可以在子类中做类似的事情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>
}
And 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; }
}
我从中得到了灵感所以答案 https://stackoverflow.com/a/57326353/10177987和这个微软文档 https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#inputtext-based-on-the-input-event
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)