Blazor에서 Bootstrap 5 모달 다이얼로그 사용하기: 단계별 따라 하기

  • 4 minutes to read

Blazor 애플리케이션에서 Bootstrap 5 모달을 활용하여 다양한 형태의 모달 UI를 만드는 방법을 단계별로 알아보겠습니다.

1단계: 새로운 Blazor Server 프로젝트 만들기

  1. 새 프로젝트 생성: Visual Studio에서 Blazor Server 프로젝트를 생성하고 프로젝트 이름을 Hawaso로 지정합니다.
  2. 프로젝트 유형 선택: Blazor Server App을 선택하여 시작합니다.

2단계: 프로젝트에 Bootstrap 5 추가하기

  1. Bootstrap 설치: 프로젝트에 Bootstrap 5를 추가합니다. wwwroot/css 폴더에 bootstrap.min.css를 다운로드하거나, CDN을 통해 추가하세요.

    <!-- wwwroot/index.html -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0/css/bootstrap.min.css" rel="stylesheet" />
    
  2. JavaScript 파일 추가: 모달 다이얼로그 동작에 필요한 Bootstrap JavaScript 파일도 추가합니다.

    <!-- wwwroot/index.html -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0/js/bootstrap.bundle.min.js"></script>
    

3단계: 기본 모달 폼 컴포넌트 만들기

Components/Demos/ModalDemo 폴더에 BasicModal.razor 파일을 추가하여 기본적인 모달을 열고 닫는 기능을 만들어봅시다.

@page "/basic-modal"

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#basicModal">
    Open Basic Modal
</button>

<div class="modal fade" id="basicModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Basic Modal</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>This is a basic modal body content.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

설명:

  • Open Basic Modal 버튼은 data-bs-toggledata-bs-target 속성을 사용해 모달을 여는 기능을 제공합니다.
  • 모달의 닫기 동작은 btn-close 클래스의 버튼과 Close 버튼에 data-bs-dismiss="modal" 속성을 추가하여 구현되었습니다.

4단계: 모달 컴포넌트 생성

Components/Demos/ModalDemo 폴더에 Modal.razor 파일을 추가합니다.

<div class="modal fade" id="@ModalId" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@Title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                @ChildContent
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@code {
    [Parameter]
    public string ModalId { get; set; } = "exampleModal";
    [Parameter]
    public string Title { get; set; } = "Modal Title";
    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

5단계: 모달 트리거 컴포넌트 생성

Components/Demos/ModalDemo 폴더에 ModalTrigger.razor 파일을 추가하여 버튼을 통해 모달을 여는 트리거를 만듭니다.

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#@TargetModalId">
    @Label
</button>

@code {
    [Parameter]
    public string Label { get; set; } = "Open Modal";
    [Parameter]
    public string TargetModalId { get; set; } = "exampleModal";
}

6단계: 모달 컴포넌트 활용하기

Pages 폴더에 ModalDemo.razor 파일을 추가하고, 앞서 만든 ModalModalTrigger 컴포넌트를 사용합니다.

@page "/modal-demo"

<ModalTrigger Label="Show Modal" TargetModalId="customModal" />

<Modal ModalId="customModal" Title="Custom Modal Title">
    <p>This is a custom modal content area.</p>
</Modal>

7단계: 조건부 모달 컴포넌트 만들기

조건부 렌더링을 통해 모달을 보였다가 숨기는 기능을 if 문을 사용하여 만들어봅시다. Components/Demos/ModalDemo 폴더에 ConditionalModal.razor 파일을 추가합니다.

@page "/conditional-modal"

<button class="btn btn-primary" @onclick="ToggleModal">Toggle Conditional Modal</button>

@if (IsModalVisible)
{
    <div class="modal show" tabindex="-1" style="display:block;">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Conditional Modal</h5>
                    <button type="button" class="btn-close" @onclick="CloseModal"></button>
                </div>
                <div class="modal-body">
                    <p>This modal is controlled by Blazor logic!</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="CloseModal">Close</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    private bool IsModalVisible = false;

    private void ToggleModal()
    {
        IsModalVisible = !IsModalVisible;
    }

    private void CloseModal()
    {
        IsModalVisible = false;
    }
}

설명:

  • 모달을 렌더링하기 전, if 조건을 확인해 보여줄지 숨길지를 결정합니다.
  • IsModalVisible 변수를 통해 모달의 표시 여부를 제어합니다.

마무리

이 가이드를 통해 Bootstrap 5 모달을 Blazor 프로젝트에 추가하고, 다양한 형태의 모달을 구현할 수 있습니다. 기본적인 모달부터 조건부 모달까지 다양한 기능을 제공하는 UI 요소를 적극적으로 활용하여 풍부하고 사용자 친화적인 인터페이스를 구축해보세요.

더 깊이 공부하고 싶다면
DevLec에서는 실무 중심의 C#, .NET, ASP.NET Core, Blazor, 데이터 액세스 강좌를 단계별로 제공합니다. 현재 수강 가능한 강좌 외에도 더 많은 과정이 준비되어 있습니다.
DevLec.com에서 자세한 커리큘럼을 확인해 보세요.
DevLec 공식 강의
C# Programming
C# 프로그래밍 입문
프로그래밍을 처음 시작하는 입문자를 위한 C# 기본기 완성 과정입니다.
ASP.NET Core 10.0
ASP.NET Core 10.0 시작하기 MVC Fundamentals Part 1 MVC Fundamentals Part 2
웹 애플리케이션의 구조와 MVC 패턴을 ASP.NET Core로 실습하며 익힐 수 있습니다.
Blazor Server
풀스택 웹개발자 과정 Part 1 풀스택 웹개발자 과정 Part 2 풀스택 웹개발자 과정 Part 3
실무에서 바로 활용 가능한 Blazor Server 기반 관리자·포털 프로젝트를 만들어 봅니다.
Data & APIs
Entity Framework Core 시작하기 ADO.NET Fundamentals Blazor Server Fundamentals Minimal APIs
데이터 액세스와 Web API를 함께 이해하면 실무 .NET 백엔드 개발에 큰 도움이 됩니다.
VisualAcademy Docs의 모든 콘텐츠, 이미지, 동영상의 저작권은 박용준에게 있습니다. 저작권법에 의해 보호를 받는 저작물이므로 무단 전재와 복제를 금합니다. 사이트의 콘텐츠를 복제하여 블로그, 웹사이트 등에 게시할 수 없습니다. 단, 링크와 SNS 공유, Youtube 동영상 공유는 허용합니다. www.VisualAcademy.com
박용준 강사의 모든 동영상 강의는 데브렉에서 독점으로 제공됩니다. www.devlec.com