How to call web api method when click on button?

sblb 1,166 Reputation points
2022-09-23T13:48:31.303+00:00

Hi,
My app : blazor wasm aps.net core5.
I would like to call api method below when I click on button in FormEdit.razor
I don't know how I call the api method when I click on button Submit.

Thanks in advance

    [HttpPost]  
        public async Task<IActionResult> Post(Developer developer)  
        {  
            YearCountECO deveco = await IncrementECODeveloperIdAsync();  
  
            developer.YearECO = deveco.YearECO;  
            developer.CountECO = deveco.CountECO;  
             
            _context.Add(developer);  
            await _context.SaveChangesAsync();  
            return Ok(developer.Id);  
        }   
  
        private async Task<YearCountECO> IncrementECODeveloperIdAsync()  
        {  
            if (!await _context.Developers.AnyAsync(d => d.Year == DateTime.Now.Year))  
            {  
                return new YearCountECO() { CountECO = 1, YearECO= DateTime.Now.Year };  
            }  
  
            int max = await _context.Developers.Where(d => d.Year == DateTime.Now.Year).MaxAsync(d => d.Count) + 1;  
            return new YearCountECO() { CountECO = max, YearECO = DateTime.Now.Year };  
        }  

Edit.razor

<FormEdit ButtonText="Update" dev="dev"  
      OnValidSubmit="@EditDeveloper" />  
  
@code {  
  
    [Parameter] public int developerId { get; set; }  
    Developer dev = new Developer();  
  
  
    protected async override Task OnParametersSetAsync()  
    {  
        dev = await http.GetFromJsonAsync<Developer>($"api/developer/{developerId}");  
    }  
  
    async Task EditDeveloper()  
    {  
        await http.PutAsJsonAsync("api/developer", dev);  
        await js.InvokeVoidAsync("alert", $"Updated Successfully!");  
        uriHelper.NavigateTo("developer");  
                         
    }  

FormEdit.razor

<EditForm Model="@dev" OnValidSubmit="@OnValidSubmit">  
    <DataAnnotationsValidator />  
  
  
 <button type="submit" @onclick="@OnSubmitEcoNumber" >Submit</button>  
  
</EditForm>  
  
@code {  
 [Parameter] public Developer dev { get; set; }  
 [Parameter] public EventCallback OnValidSubmit { get; set; }  
      
    Developer[] developers { get; set; }   

protected void OnSubmitEcoNumber()  
{  
  //It's here that I've to call the method   
}  

  
]  
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,382 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 26,191 Reputation points
    2022-09-23T14:28:47.98+00:00

    This examples comes directly from the weather forecast found in standard Blazor WSAM Visual Studio template. I moved the Web API call into a button click handler rather than the OnInitializedAsync() hander. This example is calling an external Web API endpoint with CORS enabled.

    @page "/webapiclient"  
    @inject HttpClient Http  
      
    <h1>Weather forecast</h1>  
      
    <p>This component demonstrates fetching data from the server.</p>  
      
    @if (forecasts == null)  
    {  
        <div>  
            <button id="mybutton" class="btn btn-primary" @onclick="GetWeatherForecast">Click me</button>  
        </div>  
    }  
    else  
    {  
        <table class="table">  
            <thead>  
                <tr>  
                    <th>Date</th>  
                    <th>Temp. (C)</th>  
                    <th>Temp. (F)</th>  
                    <th>Summary</th>  
                </tr>  
            </thead>  
            <tbody>  
                @foreach (var forecast in forecasts)  
                {  
                    <tr>  
                        <td>@forecast.Date.ToShortDateString()</td>  
                        <td>@forecast.TemperatureC</td>  
                        <td>@forecast.TemperatureF</td>  
                        <td>@forecast.Summary</td>  
                    </tr>  
                }  
            </tbody>  
        </table>  
    }  
      
    @code {  
      
        private IEnumerable<WeatherForecast> forecasts;  
      
        private async Task GetWeatherForecast()  
        {  
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("https://localhost:44352/WeatherForecast");  
        }  
      
        public class WeatherForecast  
        {  
            public DateTime Date { get; set; }  
      
            public int TemperatureC { get; set; }  
      
            public string Summary { get; set; }  
      
            public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);  
        }  
    }  
    

    As recommended in your other posts, please make an effort to read the openly published documentation or go through a few beginning level Blazor tutorials. Learning Blazor is far more effective than asking the community to create custom learning content or guessing.