Search code examples
c#.net-coreasp.net-core-mvcblazor

Pass Function as a parameter in ASP.NET Core MVC Blazor


I am using Bootstrap 5 modal in my ASP.NET Core 6 project to show alert messages.

I want to generalize the code and use it in different .razor components of my ASP.NET Core MVC app.

Here is the code of my message.razor component:

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">ALERT !</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                Are You Sure You Want To Delete ?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" @onclick="Function" data-bs-dismiss="modal" class="btn btn-danger">Delete</button>
            </div>
        </div>
    </div>
</div>

At onclick function I want to pass the delete function with parameter, like this

@onclick="(e => OnDelete(emp.TypeOfId))"

to the message.razor component from another .razor component.

<MessageComponent Function="OnDelete(emp.TypeOfId)"></MessageComponent>

Solution

  • You can add an Action parameter to the MessageComponent that will be called when the button is clicked:

    <button @onclick="Function">Button</button>
    
    @code {
        [Parameter] public Action Function { get; set; }
    }
    

    Then from the parent you can pass the parameter like this:

    <MessageComponent Function="@(() => OnDelete(emp.TypeOfId))"></MessageComponent>
    

    Update:

    In Blazor it is preferred to use EventCallback instead of Action so the previous example can become:

    Child component:

    <button @onclick="DeleteClicked">Delete</button>
    
    @code {
        [Parameter] public EventCallback DeleteClicked { get; set; }
    }
    

    Parent component:

    <MessageComponent DeleteClicked="@(() => OnDelete(emp.TypeOfId))"></MessageComponent>