'Making request without refreshing page with blazor
Please i am new to blazor, I am building a pet project and i want to make a call to the server to do so validation if the text entered into an input textbox is equals 10. I know in a normal MVC project we will be using AJAX to make this request, But i can't wrap my head around what will be used in blazor. Thanks
Solution 1:[1]
- Add Country class:
public class Country { public string? Name { get; set; } public bool Saving { get; set; } }
- Add CsValidation Class:
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; namespace BlazorApp3 { public class CsValidation : ComponentBase { private ValidationMessageStore? messageStore; [CascadingParameter] public EditContext? CurrentEditContext { get; set; } protected override void OnInitialized() { if (CurrentEditContext == null) { throw new InvalidOperationException( $"{nameof(CsValidation)} requires a cascading " + $"parameter of type {nameof(EditContext)}. " + $"For example, you can use {nameof(CsValidation)} " + $"inside an {nameof(EditForm)}."); } messageStore = new(CurrentEditContext); CurrentEditContext.OnValidationRequested += (s, e) => messageStore.Clear(); CurrentEditContext.OnFieldChanged += (s, e) => messageStore.Clear(e.FieldIdentifier); } public void DisplayErrors(Dictionary<string, List<string>> errors) { if (CurrentEditContext != null) { foreach (var err in errors) { if (messageStore != null) messageStore.Add(CurrentEditContext.Field(err.Key), err.Value); } CurrentEditContext.NotifyValidationStateChanged(); } } public void ClearErrors() { if (messageStore != null && CurrentEditContext != null) { messageStore.Clear(); CurrentEditContext.NotifyValidationStateChanged(); } } } }
- Add razor page to test add new country validation:
@page "/CreateCountry" <EditForm Model="@NewCountry" OnValidSubmit="OnSave"> <CsValidation @ref="CsValidation" /> <DataAnnotationsValidator /> <div class="form-group mb-3"> <label class="form-label">Country Name</label> <InputText class="form-control" @bind-Value="@NewCountry?.Name" /> <ValidationMessage For="@(() => NewCountry?.Name )" class="small" /> </div> <hr /> <div class="d-grid gap-2"> <button type="submit" class="btn btn-fill btn-danger">Save</button> </div> </EditForm> @code { public Country? NewCountry { get; set; } private CsValidation? CsValidation { get; set; } public async Task OnSave() { try { CsValidation.ClearErrors(); var errors = new Dictionary<string, List<string>>(); //Test if country added befor if (CountryService.IsNameAdded(NewCountry?.Name)) //Add validation error errors.Add(nameof(NewCountry.Name), new() { "This country has been added." }); if (errors.Any()) //Show validation errors CsValidation.DisplayErrors(errors); else { //Save new country } } catch (Exception ex) { //Handel execption } } }
You can update last razor file to get data from api service:
@page "/CreateCountry" @inject HttpClient http <EditForm Model="@NewCountry" OnValidSubmit="OnSave"> <CsValidation @ref="CsValidation" /> <DataAnnotationsValidator /> <div class="form-group mb-3"> <label class="form-label">Country Name</label> <InputText class="form-control" @bind-Value="@NewCountry?.Name" /> <ValidationMessage For="@(() => NewCountry?.Name )" class="small" /> </div> <hr /> <div class="d-grid gap-2"> <button type="submit" class="btn btn-fill btn-danger">Save</button> </div> </EditForm> @code { Country? NewCountry { get; set; } private CsValidation? CsValidation { get; set; } public async Task OnSave() { try { CsValidation.ClearErrors(); var errors = new Dictionary<string, List<string>>(); //Call api service and get data var response = await http.GetFromJsonAsync<bool>($"/api/iscountryadded?name={NewCountry?.Name}"); //Test if country added befor if (response) //Add validation error errors.Add(nameof(NewCountry.Name), new() { "This country has been added." }); if (errors.Any()) //Show validation errors CsValidation.DisplayErrors(errors); else { //Save new country } } catch (Exception ex) { //Handel execption } } } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |