1

I want to show alert after a button click in Blazor. Below is the html and server side code

 <div class="form-group col-md-12 ">
            <button class="btn btn-primary" @onclick="InsertForecast"> Submit</button>
        </div>

 public async Task InsertForecast()
        {
//want to add the alert here


 bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
}

I tried adding using Microsoft.JSInterop in the code behind file but the JsRuntime object giving the following error

Object does not contain a definition for InvokeAsync and the best extension method overload JSObjectreferenceExtension.InvokeAsync expects parameter of type 'IJsObjectreference'

Quango
  • 12,338
  • 6
  • 48
  • 83
sandeep.mishra
  • 825
  • 4
  • 19
  • 40
  • I tried that approach but I am getting an error Object doesnot contain a definition for invokeasync – sandeep.mishra Apr 06 '21 at 05:18
  • What is the error? And can you add in the question whatever you have tried so far – Vivek Nuna Apr 06 '21 at 05:18
  • @Vivek, Added the error message .Please check – sandeep.mishra Apr 06 '21 at 05:26
  • you need to define the confirm function in a separate js file and include it – Vivek Nuna Apr 06 '21 at 05:31
  • be sure you has `@inject IJSRuntime JsRuntime`. I just check and work. @vivek , it's not necesary create a separate js file – Eliseo Apr 06 '21 at 06:51
  • @Eliseo yes you are right, we don’t need separate file. But it’s for separation of code and better maintainability. JS code at separate place – Vivek Nuna Apr 06 '21 at 06:52
  • @Eliseo, the code is still not working for me .Can you please give some sample code or a fiddle for that – sandeep.mishra Apr 06 '21 at 08:43
  • it's the first time I use this online-editor: https://blazorfiddle.com/s/2hsr04eo but really it's only your code and comment – Eliseo Apr 06 '21 at 09:07
  • Thanks a ton Eliseo, This works if the code is in same file but will it work if there is a separate code file for the html and I have to showthe alert on button click event code behind ? – sandeep.mishra Apr 06 '21 at 10:24
  • I would recommend learning the Blazor way. You could easily create a reusable dialog component, or download a free open source widget like blazored: https://github.com/Blazored/Modal – Steve Greene Apr 06 '21 at 15:58
  • To inject IJSRuntime in a Blazor component I think that should be `[Inject]private IJSRuntime JsRuntime {get;set;}` :https://blazor-university.com/dependency-injection/injecting-dependencies-into-blazor-components/ – Eliseo Apr 06 '21 at 16:19
  • Thanks it is nowworking as expected :) – sandeep.mishra Apr 07 '21 at 07:12

0 Answers0