xy z
xy z

Reputation: 51

How to invoke js in blazor anywhere?

I'm try to call js on a button onclick event in blazor (server), but I got the error:

JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendererd. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.

And I'm using Server render mode.

<component type="typeof(App)" render-mode="Server" />

If I use client render mode, it works correctly.

Upvotes: 2

Views: 3228

Answers (2)

Andrea Spada
Andrea Spada

Reputation: 11

I'm using the server version and in the follow example I have the same errore exposed above.

File .razor:
      <RadzenTabs SelectedIndex="0" Change=@(args => OnChangeRadzenTab(args))>

File.cs:
        async void OnChangeRadzenTab(int value)
        {
            switch (value)
            {
               case 0:
                   await jsRuntime.InvokeVoidAsync("eval", $@"document.getElementById(""NameOfField"").focus()");
                   break;
               

But in the follow one, instead, the code run. Why there are these differences of behavour?

File .razor:
        <RadzenMask Mask="**/**/****" Pattern="[^0-9]" Name="EndDate" Id="EndDate"
                    @bind-Value=@EndDate  @onfocusout=@(args => OnFocusOutEndDate(args)) /> 

File.cs:
        async void OnFocusOutEndDate(FocusEventArgs? value)
        {
            if (!LibB.CheckDate(EndDate))
            {
                await jsRuntime.InvokeVoidAsync("eval", $@"document.getElementById(""EndDate"").focus()");
                Error = true;
            }
        }   

Upvotes: 0

Stoway
Stoway

Reputation: 11

While a Blazor Server app is prerendering, certain actions, such as calling into JavaScript, aren't possible because a connection with the browser hasn't been established. Components may need to render differently when prerendered. For more information, see the Detect when the app is prerendering section.

reference:https://learn.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1

Upvotes: 1

Related Questions