I've discovered that my Blazor design for this particular context is unusual, and I'm having trouble figuring out how to address it.
This is my data class models:
Data class model holder of database-fetched data
[Keyless]public class Specs{ [Column("id")] public string? ID { get; set; } [Column("name")] public string? Name { get; set; } [Column("value")] public string? Value { get; set; } [Column("rank")] public int Rank { get; set; }}Data class model holder of user-modified data
public class SpecsEntryHolder(string? id, string? n, string? val, int rank){ public string? ID { get; set; } = id; public string? Name { get; set; } = n; public string? Value { get; set; } = val; public int Rank { get; set; } = rank;}Redefine those data class models as a List
public List<Specs> SpecsList { get; set; } = [];public List<SpecsEntryHolder> SpecsEntryHolderList { get; set; } = [];I cloned the data through this approach:
// SpecsList has already been fed with the database records.SpecsEntryHolderList = SpecsList.Select(v => new SpecsEntryHolder(v.ID, v.Name, v.Value, v.Rank)).ToList();In the Razor UI page:
<EditForm EditContext="editContext" OnValidSubmit="UpdateSomething" FormName="edit" Enhance><DataAnnotationsValidator /> @foreach (var specs in SpecsEntryHolderList) {<div class="col-12 col-sm-6 col-lg-3 mb-3 d-flex flex-column align-items-start"><label for="someText" class="form-label text-nowrap fw-bold">@($"{specs.Name}")</label><InputText id="@($"{specs.ID}")" @bind-Value="specs.Value" @onblur="FormatOnBlurSpecs" class="form-control form-control-sm" /><ValidationMessage For="() => specs.Value" class="text-danger" /></div> }</EditForm>Here's what it looks like:
I was hoping this would work, but it doesn’t:
private void FormatOnBlurSpecs(FocusEventArgs e){ foreach (var spec in SpecsEntryHolderList) { var fieldIdentifier = new FieldIdentifier(spec, nameof(spec.Value)); if (string.IsNullOrWhiteSpace(spec.Value)) { messageStore!.Add(fieldIdentifier, $"{spec.Name} is required."); } messageStore?.Clear(fieldIdentifier); }}I was trying to programmatically handle the validation for a certain field when it's empty through this approach (if it is possible), but I can't achieve what I wanted. I already know that the basic implementation of built-in validation in Blazor is through a set of fields that corresponds to each text entry. The approach I'm trying to achieve is to provide a custom validation instead, with a reconceptualized field binding source. I was trying to figure out this limitation and its corresponding workaround since it is obviously a dynamic setup of InputText.
Here is my additional question, aside from the title question for this context:
- Is there a workaround for this approach? If so, how can it be implemented properly?
