bisoy27
bisoy27

Reputation: 11

Blazor EventCallback<T> from a SSR parent to an InteractiveServer Child Component is Null

I have a SSR Parent component with a Child component with InteractiveServer render mode. I need this child component to be interactive so that I can bind to events like @onclick etc. I want to pass data/value back to the parent using EventCallback but this delegate is never set I guess due to different render modes, is there another way to do this?

Parent.razor

<Child
  @rendermode="InteractiveServer"
  OnNameEntered="@DisplayName"/>

@code {
  
  public void DisplayName(string result) {
     Console.WriteLine($"Result is {result}");
  }
}

Child.razor

<input @bind="name"/>
<button type="button" @onclick="NameEntered">Click</button>

@code {
  [Parameter]
  public EventCallback<string> OnNameEntered { get; set; }

  private string name;
 
  public async Task NameEntered() {
    await OnNameEntered.InvokeAsync(name);
  }

I tried removing the InteractiveRender mode on the child and the delegate would properly pass to the child but then it would remove all interactivity within that component.

Upvotes: 1

Views: 238

Answers (1)

Qiang Fu
Qiang Fu

Reputation: 8616

You coud try not use InteractiveServer, then using submit form to make button work in SSR. Try following:
Parent.razor

<Child NameChanged="DisplayName"/>
@code {
    public void DisplayName(string result)
    {
        Console.WriteLine($"Result is {result}");
    }
}

Child.razor

<form method="post" @onsubmit="NameEntered" @formname="form1">
    <AntiforgeryToken />
    <InputText @bind-Value="name" />
    <button type="submit">Submit</button>
</form>

@code {
    [Parameter]
    public EventCallback<string> NameChanged { get; set; }

    [SupplyParameterFromForm]
    private string name { get; set; }

    protected override void OnInitialized() => name ??= "";

    public async Task NameEntered() {
        await NameChanged.InvokeAsync(name);
    }
}

Test result
enter image description here

By the way, I think the better way is to make the authentication provider working on both Interactive and SSR.

Upvotes: 0

Related Questions