Search code examples
c#razorblazor

Creating a popup in Blazor using C# method


I have a simple page index.razor with a button:

<a class="btn btn-login" @onclick="RedirectPage" >Log in</a>

<div
    @bind-Visible="@InvalidLogin"
    BodyText="Error">
</div>

@code{
    InvalidLogin {get; set;} = false;
}

Where the function RedirectPage checks if values are valid. If they are not, I want a popup giving information:

private void RedirectPage
{
    this.InvalidLogin = true;
}

This function is in the index.razor.cs and has been added with @using in the correct namespace.

How can I create it so that a popup shows up whenever the button is clicked?


Solution

  • You can create a simple popup (or modal dialog) component. Below, I wrote a sample popup razor component using Bootstrap 5 toast component.

    Popup.razor file

    @{
        var showClass = IsVisible ? "d-block" : "d-none";
    }
    
    <div class="toast-container p-3 @showClass" data-bs-autohide="true" data-bs-delay="5000">
        <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <strong class="me-auto">@HeaderText</strong>
                <button type="button" class="btn-close" aria-label="Close" @onclick="Close"></button>
            </div>
    
            <div class="toast-body">
                @BodyText
            </div>
        </div>
    </div>
    
    @code {
        [Parameter]
        public bool IsVisible { get; set; }
    
        [Parameter]
        public EventCallback<bool> IsVisibleChanged { get; set; }
    
        [Parameter]
        public string? HeaderText { get; set; }
    
        [Parameter]
        public string? BodyText { get; set; }
    
        public void Show(string bodyText, string headerText = "")
        {
            HeaderText = headerText;
            BodyText = bodyText;
            IsVisible = true;
            StateHasChanged();
        }
    
        private void Close()
        {
            HeaderText = string.Empty;
            BodyText = string.Empty;
            IsVisible = false;
            StateHasChanged();
        }
    }
    

    Using the Popup razor component in your code:

    <a class="btn btn-login" @onclick="RedirectPage" >Log in</a>
    
    <Popup @ref="popupRef" />
    
    @code{
        private Popup popupRef;
        
        private void RedirectPage()
        {
            // Shows the popup at the center of the screen
            popupRef.Show("Popup body text");
        }
    }