3

Blazor server app (.Net 5.0), Dapper

On my (Razor) form, I have a field "Name" that I need to check at entry time. On page load, OnInitializedAsync() I fetch all names from the database as List<string> names. And then when the user inputs a new name I need to fire CheckNames() method to check if the value of <InputText> exists in the list - names.Contains(inputValue) - where inputValue is the value from <InputText> tag. And if exists then show a message saying that value already exists. The problem is - I don't know how to refer to HTML tags from C# code. Or maybe my validation logic is wrong.

Details: I fetch all names at page load because it will be faster to check name existence in a list in the memory with onchange event, rather than querying SQL every time for every single letter when a user types a new name in the form. Another approach is could be to check name existence in SQL at the form submit stage. However, I lean towards the "check at typing" method from the fetched list.

Here is my simplified code:

    <div class="container float-sm-left">
        <EditForm Model="@partner" OnValidSubmit="@InsertItem" class="form-horizontal">
            <DataAnnotationsValidator />
            <div class="form-group row">
                <label class="col-form-label col-sm-4 text-right">Name</label>
                <div class="col-sm-8">
                    <InputText @bind-Value="partner.Name" class="form-control" id="pname" name="pname" />
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
            <button @onclick="@Cancel" type="reset" class="btn btn-secondary">Cancel</button>
        </EditForm>
    </div>

    
    @code {
        private Partner partner = new Partner();
        private List<string> partnerNames = new List<string>();
        
        void CheckName()
        {
            if(partnerNames.Contains(inputValue))  // inputValue - a value from <InputText>
            {
                // show validation message and prevent form submit
            }
        }
        
        protected override async Task OnInitializedAsync()
        {
            var partners = await PartnerService.GetAllAsync();
            partnerNames = partners.Select(x => x.Name).ToList();
        }
    
        protected async Task InsertItem()
        {
            await PartnerService.InsertAsync(partner);
            await BlazoredModal.Close(ModalResult.Ok<Partner>(partner));
        }
    
        void Cancel()
        {
            BlazoredModal.Close(ModalResult.Cancel());
        }
    
        [CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; }
        string Message { get; set; }
    }

How to check the existence of the input value and validate it?

Elshad Shabanov
  • 483
  • 10
  • 17

0 Answers0