• A
  • B
  • A
  • B
  • A
  • B
  • How to bind event in MarkupString

    24 Views Asked by At
    @if(!string.IsNullOrEmpty(_markup))
    {
        @((MarkupString)_markup)
    }
    
    @code {
        public string _markup = "<ul><li class='li-a'>A</li><li class='li-a'>B</li></ul>";
    }
    

    I want bind event in MarkupString.

    I'm leaving a question because I don't have enough knowledge about Blazor, and because of that, I don't have enough keywords to search on Google.

    ex)

    public string _markup = "<ul><li class='li-a' @onclick="(e) => clicktext(e)">A</li><li class='li-a' @onclick="(e) => clicktext(e)">B</li></ul>";
    
    
        void clicktext(object e)
        {
            //code here..
        }
    
    1

    There are 1 best solutions below

    0
    MrC aka Shaun Curtis On BEST ANSWER

    You can't do it with MarkupString. If you want interactive behaviour you need to use a RenderFragment. As you haven't provided any context to your question, I don't know if this remotely fits your use case.

    Here's a quick example:

    @page "/"
    @using Microsoft.AspNetCore.Components.Rendering
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    @_markup
    
    @code{
        private RenderFragment _markup => (__builder) =>
        {
        <ul>
            <li class="li-a" @onclick="OnClickText">A</li>
            <li class="li-a" @onclick="OnClickText">B</li>
        </ul>
        };
    
        private Task OnClickText(MouseEventArgs e)
        {
            //code here..
            return Task.CompletedTask;
        }
    }