Home > Software engineering >  How to properly add an OnClick handler on Blazor RenderFragment CodeBehind
How to properly add an OnClick handler on Blazor RenderFragment CodeBehind

Time:09-16

As part of my project's specific need, I have to use render fragments on Blazor Code Behind (.cs file). Using the code below, I am able to render a button properly, however the @onclick handler seems to not be working or getting hit.

How do I properly add an onclick in a renderfragment builder?

RenderFragment template = builder =>
{
    builder.AddMarkupContent(1, $"<button class='btn btn-success' @onclick='() => OnToastClick({toastDetail.Key})'>{toastDetail.Key}</button>");
};

CodePudding user response:

AddMarkupContent() adds HTML markup, it does not parse Razor content.

The best I could come up with:

RenderFragment template(IComponent owner, ToastDetail toastDetail)
{
    return builder =>
    {
        builder.OpenElement(1, "button");
        builder.AddAttribute(2, "class", "btn btn-success");
        builder.AddAttribute(3, "onclick",
            Microsoft.AspNetCore.Components.EventCallback.Factory.Create(owner, 
               () => OnToastClick(toastDetail.Key)));
        builder.AddContent(4, toastDetail.Key);
        builder.CloseElement();
    };
}

and then you can use it like

  @template(this, toastDetail)
  • Related