Exercise: Building an Interactive To-Do List with Add, Mark Done, and Delete in .NET 8.0 Blazor
Exercise: Building an Interactive To-Do List with Add, Mark Done, and Delete in .NET 8.0 Blazor
This exercise focuses on implementing a functional To-Do List that allows users to add new tasks, mark existing tasks as completed, and remove tasks from the list. You'll work with Razor Components, custom C# classes, data binding, and event handling.
Preparation: Your Development Environment
Before you begin, ensure your system is set up:
Visual Studio 2022:
- Ensure Visual Studio 2022 is installed and updated (version 17.8+).
- Confirm the "ASP.NET and web development" workload is selected.
.NET 8.0 SDK:
- Verify the .NET 8.0 SDK is installed. Open Command Prompt (CMD) and type
dotnet --list-sdks. You should see8.0.xlisted.
The Feature-Rich To-Do List Exercise
Follow each step sequentially.
Phase 1: Project Setup (If you don't have a Blazor project ready)
If you already have a .NET 8.0 Blazor Web App (e.g., from previous exercises), you can skip to Phase 2.
1. Open Command Prompt (CMD):
- Type
cmdin your Windows Start Menu search bar and pressEnter.
2. Navigate to Your Projects Folder:
- For example:
cd C:\Users\YourUser\Documents\Projects(replaceYourUserwith your actual username).
3. Create the .NET 8.0 Blazor Web App Project:
Type the following command and press Enter:
dotnet new blazor -n BlazorFeatureTodoList --interactivity WebAssembly --empty false --no-https false
--interactivity WebAssembly: Ensures interactive components run client-side.
Observe: Project creation messages.
4. Open the Project in Visual Studio 2022:
- Open a new instance of Visual Studio 2022.
- Select "Open a project or solution".
- Navigate to your new project folder (e.g.,
C:\Users\YourUser\Documents\Projects\BlazorFeatureTodoList). - Select
BlazorFeatureTodoList.slnand click "Open".
Phase 2: Implementing Add, Mark Done, and Delete Functionality
Now, we'll add the core features to your To-Do list component.
1. Create Your To-Do List Component File:
- In Visual Studio's "Solution Explorer," right-click on the
Componentsfolder, then click on thePagessubfolder. - Select "Add" -> "Razor Component...".
- Name it
TodoList.razorand click "Add".
2. Add the Complete To-Do List Code to TodoList.razor:
- Open
TodoList.razor. - Crucial for .NET 8.0 Interactivity: Add
@rendermode InteractiveWebAssemblyat the very top of the file to ensure client-side interactivity. - Paste the following code into
TodoList.razor, replacing any existing content:
@rendermode InteractiveWebAssembly @* This component will run interactively on the client using WebAssembly *@ @page "/todo" <h1>My Blazor To-Do List</h1> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="What needs to be done?" @bind="newItemText" @onkeyup="HandleKeyUp" /> <button class="btn btn-primary" @onclick="AddItem">Add To-Do</button> </div> @if (todoItems.Any()) { <h2>Tasks:</h2> <ul class="list-group"> @foreach (var item in todoItems) { <li class="list-group-item d-flex justify-content-between align-items-center"> <div class="form-check"> <input type="checkbox" class="form-check-input" @bind="item.IsDone" id="@($"todoItem_{item.Id}")" /> <label class="form-check-label @(item.IsDone ? "text-muted text-decoration-line-through" : "")" for="@($"todoItem_{item.Id}")"> @item.Text </label> </div> <button class="btn btn-danger btn-sm" @onclick="() => RemoveItem(item)">Delete</button> </li> } </ul> } @else { <p class="text-info">No tasks yet! Add something to your list.</p> } @code { // A simple class to represent a single To-Do item // It now has an Id (unique), Text, and IsDone status. private class TodoItem { public Guid Id { get; set; } = Guid.NewGuid(); // Unique ID for each item public string Text { get; set; } public bool IsDone { get; set; } } // This is our C# list that will hold all the To-DoItem objects private List<TodoItem> todoItems = new List<TodoItem>(); // This variable will temporarily hold the text typed into the input box private string newItemText = ""; // This method runs automatically when the component first starts up protected override void OnInitialized() { // Add a couple of starting To-Do items todoItems.Add(new TodoItem { Text = "Learn Blazor basics" }); todoItems.Add(new TodoItem { Text = "Practice coding exercises", IsDone = true }); // Example: This one starts as done todoItems.Add(new TodoItem { Text = "Build a cool project" }); } // This method runs when the "Add To-Do" button is clicked private void AddItem() { // Check if the input box actually has some text (not just empty spaces) if (!string.IsNullOrWhiteSpace(newItemText)) { // Create a new TodoItem object and add it to our list todoItems.Add(new TodoItem { Text = newItemText }); newItemText = ""; // Clear the input box so it's ready for the next task } } // This method allows adding an item by pressing Enter in the input field private void HandleKeyUp(KeyboardEventArgs e) { if (e.Key == "Enter") { AddItem(); } } // This method runs when a "Delete" button is clicked for a specific item private void RemoveItem(TodoItem itemToRemove) { todoItems.Remove(itemToRemove); // Remove the specific item from the list } }
- Save the file: Press
Ctrl + S.
3. Update the Navigation Menu:
- In "Solution Explorer," navigate to
Components/Layout. - Double-click
NavMenu.razorto open it. - Below the "Weather"
NavLink, add this new menu item:
<div class="nav-item px-3"> <NavLink class="nav-link" href="todo"> <span class="oi oi-list-rich" aria-hidden="true"></span> To-Do List </NavLink> </div>
- Save the file: Press
Ctrl + S.
4. Add CSS Styling for "Mark as Done":
- In "Solution Explorer," navigate to
wwwroot/css. - Double-click
app.cssto open it. - Scroll to the very bottom and add this CSS rule:
/* Style for items marked as bought/done */ .text-decoration-line-through { text-decoration: line-through; /* Draws a line through the text */ } .text-muted { color: #888 !important; /* Makes the text grey, !important for Bootstrap override */ font-style: italic; /* Makes the text italic */ }
- Save the file: Press
Ctrl + S.
Phase 3: Run and Test All Functionalities
Now, launch your application and thoroughly test the add, mark as done, and delete features.
1. Run the Application from Visual Studio:
- Click the green "Play" button in Visual Studio to launch your Blazor app.
Observe: Your browser will open. On the left navigation, click "To-Do List".
2. Test "Add" Functionality:
- Observe: You should see the initial items: "Learn Blazor basics," "Practice coding exercises" (crossed out and grey), and "Build a cool project."
- Type a new item (e.g., "Schedule meeting") into the input box.
- Click the "Add To-Do" button or press
Enter(due to theHandleKeyUpmethod).
Observe: Your new item should instantly appear at the bottom of the list.
3. Test "Mark as Done" Functionality:
- Click the checkbox next to "Learn Blazor basics."
Observe: The text should immediately change to grey and have a strike-through.
- Click the checkbox again.
Observe: The styling should revert, showing the item as not done.
4. Test "Delete" Functionality:
- Click the "Delete" button next to "Build a cool project."
Observe: The item should instantly disappear from the list.
- Continue deleting items until the list is empty.
Observe: When the list is empty, the "No tasks yet! Add something to your list." message should appear.
Congratulations! You've successfully implemented a fully functional To-Do List in Blazor, covering key interactive features and understanding how C# and HTML work together in Razor Components!
Comments
Post a Comment