Blazor: How to use a onclick event in MarkupString

Viewed 34

The click-event is not working. I don't know why.

In a foreach I create a String:

      html += $"<div style='padding: 5px;' @onclick='() => TerminClick({term.Sinr})'>";{date}</div>";

and put it into a MarkupString object:

      _terminContent = new MarkupString(html);

At the html I implement the content:

      @_terminContent 

I got the method TerminClick(int id)

    public void TerminClick(int id)
    {
        logger.LogWarning($"Termin: {id}");
    }

At Chrome Dev Tools I check the code: enter image description here

I tried also without parameter {term.Sinr} respectively int id and that also is not working. I set a breakpoint into TerminClick() it's never hit and also at the console logger.LogWarning(..) is never logged.

I tried also using @onclick="@TerminClick(..)".

How do I get the click event working using a MarkupString?

3 Answers

I fixed it through using a loop at the razor file:

        @foreach (var term in terms)
        {
            <div style='padding: 5px;' @onclick="@(() => TerminClick(@term.Sinr))">@term.Date</div>
        }

Now it works fine.

I think it would be good for future reference to explain why this did not work. Blazor is not dynamic. Everything is predefined by means of compilation.

MarkupString only renders a string as HTML Markup. Nothing else will be attached here.

In your example, a proper way of adding elements to a parameter is to use a RenderFragment instead of a string, and appending to that RenderFragment.

Example component:

@myObject

@code {
    RenderFragment myObject { get; set; }

    protected override void OnInitialized()
    {
        for (int i = 0; i < 10; i++)
        {
            int thisIndex = i;
            myObject += @<div>@thisIndex</div>;
        }
    }
}

The '@' character is important here, as this will be treated like any other Blazor element, and not as a string.

The best approach in this scenario is as figured out (looks better too):

@for (int i = 0; i < 10; i++)
{
    int thisIndex = i;
    <div>@thisIndex</div>;
}

@code {
}
Related