question

sblb-6958 avatar image
0 Votes"
sblb-6958 asked ZhiLv-MSFT commented

How to call web api method when click on button?

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 
 }

    
 ]





dotnet-aspnet-core-blazor
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AgaveJoe avatar image
0 Votes"
AgaveJoe answered ZhiLv-MSFT commented

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.

· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for your information.

Please read my first email, in Edit.razor I've already made Get

    protected async override Task OnParametersSetAsync()
      {
          dev = await http.GetFromJsonAsync<Developer>($"api/developer/{developerId}");
      }


And as you can see always in Edit.razor I've put EditDeveloper to fill all data in database table (Developer).

When I OnValidSubmit="@EditDeveloper" is validated all variable is fill in table;

BUT I want to fill the variable ECO only when the user validate the button Submit from FormEdit this means that the user chooses whether or not to take an ECO number






0 Votes 0 ·

Unfortunately, the code you've shared is nonsensical so I have no idea what you're doing but this is your original question.

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.

I provided an example of calling Web API and populating the DOM.

Now you're asking how solve a logical problem. Solving problems is the main task of a developer. I have no intention of designing your code.

Ironically, the code I shared above contains the pattern you are looking for... it is called an "if". If the ECO is valid then let the user "take the ECO number". I have no idea what "take the ECO number" means but what ever that action is all you need is an "if". You know, like the Beatles song.

Are you actually asking how to pass data in Blazor WASM using routes? Or are you asking how to validate in Blazor WASM?

ASP.NET Core Blazor forms and input components


0 Votes 0 ·

As I already explain there are 2 columns ECR AND ECO.
ECR has been done with your proposition.

Right now I want to do the same thing that ECR for ECO with one difference that's user can choose to put or not the number ECO WITH APi METHOD.
I repeat again Yellow submarine, Yellow....

0 Votes 0 ·
Show more comments