我是第一次使用 Blazor(也是几年来我第一次使用 .NET,所以我生疏了),我和我的团队决定与 Blazor 一起使用的附加组件库是泥浆刀。现在我正在处理一个具有自动完成组件的页面。
我想要做的是使用自动完成功能来拉出用户可以添加到列表中的书籍列表。至少一本书必须在列表中。我的问题是,由于 MudAutocomplete 的工作原理,我无法将其绑定到列表,因此我将 Book 附加到单击事件的列表中。但是,点击提交按钮并没有点击我实施的任何一个验证,我似乎无法弄清楚为什么。
我有以下代码:
<MudForm @ref="form" @bind-isValid="@success" bind-errors="@errors">
<MudAutocomplete T="Book" Label="Select Book(s)" ValueChanged="@(b => AppendBookToList(b))" SearchFunc="@SearchBooks" MinCharacters="4" ToStringFunc="@(b => b == null ? null : $"{b.Name + " by " + b.Author}")" Validation="@(new Func<string, IEnumerable<string>>(ValidateRequiredBooks)">
</MudAutocomplete>
<!-- List books that were selected from the autocomplete -->
@foreach (var b in Books)
{
<MudChip Color="Color.Primary" OnClose="RemoveRequester" Text="b.Id">@b.Name by @b.Author</MudChip>
}
<!-- I guess use this area below to secretly bind the Books field? Not sure how to display the validation error otherwise -->
<MudField @bind-Value="@Books"></MudField>
...
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto" OnClick="@(() => form.Validate())">Submit</MudButton>
</MudForm>
...
@code {
...
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
[BooksValidation(ErrorMessage = "At least one Book required.")]
public List<Book> Books { get; set; }
...
// This is not firing
private IEnumerable<string> ValidateRequiredBooks(string value)
{
if (Books.Count == 0)
{
yield return "At least one Book must be selected.";
yield break;
}
}
}
Books
我还为我的变量创建了以下自定义验证属性:
public class BooksValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Breakpoint here isn't getting hit
var listValue = value as List<Book>;
if (listValue != null && listValue.Count != 0)
{
return null;
}
else
{
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
}
关于为什么这些根本不起作用的任何想法?它把我逼到了墙角