Exercise 4: Enhanced Two-Way Data Binding with Conditional Logic and Nested Display

Blazor Exercise 4: Enhanced Two-Way Data Binding with Conditional Logic and Nested Display

Exercise 4: Enhanced Two-Way Data Binding with Conditional Logic and Nested Display

You've mastered the basics of two-way data binding. Now, let's take it a step further! This exercise will challenge you to build a more comprehensive form that utilizes multiple data-bound properties, implements conditional rendering, and provides a real-time preview of the entered data. This will solidify your understanding of how Blazor components react to state changes.

✅ Goal:

Build a simple "Profile Preview" form using multiple @bind properties, various input types, a toggle button to show/hide a live preview, and conditional rendering—all within a single Blazor page.

๐Ÿงฉ Concepts Covered:

  • @bind and @bind:event for different update timings.
  • Working with various HTML input types: text, number, select (dropdown), and checkbox.
  • Implementing conditional rendering using @if blocks to show/hide UI elements.
  • Creating a real-time form preview that updates as the user types.
  • Organizing UI logic and data models within a single component.

๐Ÿ”ง Steps:

Step 1: Create a new Razor page named ProfileForm.razor

Create a new Razor component file named ProfileForm.razor in your Pages folder.

Paste the following code into ProfileForm.razor:


<!-- ProfileForm.razor -->
@page "/profile-form"

<h2 class="heading2">User Profile Form</h2>

<div class="form-container">
    <label for="nameInput">Name:</label>
    <input id="nameInput" type="text" @bind="user.Name" @bind:event="oninput" placeholder="Your Name" />

    <label for="ageInput">Age:</label>
    <input id="ageInput" type="number" @bind="user.Age" placeholder="Your Age" />

    <label for="genderSelect">Gender:</label>
    <select id="genderSelect" @bind="user.Gender">
        <option value="">-- Select Gender --</option>
        <option>Male</option>
        <option>Female</option>
        <option>Other</option>
    </select>

    <label>
        <input type="checkbox" @bind="user.IsSubscribed" />
        Subscribe to newsletter
    </label>

    <button @onclick="TogglePreview" class="blazor-button">
        @(showPreview ? "Hide Preview" : "Show Preview")
    </button>
</div>

@if (showPreview)
{
    <div class="preview-box">
        <h3>Live Profile Preview</h3>
        <p><b>Name:</b> @user.Name</p>
        <p><b>Age:</b> @user.Age</p>
        <p><b>Gender:</b> @user.Gender</p>
        <p><b>Subscribed:</b> @(user.IsSubscribed ? "Yes" : "No")</p>
    </div>
}

@code {
    // Boolean to control the visibility of the preview box
    bool showPreview = false;

    // Instance of our UserProfile model to hold form data
    UserProfile user = new();

    // Method to toggle the showPreview boolean
    void TogglePreview()
    {
        showPreview = !showPreview;
    }

    // Define the UserProfile model class directly in the @code block for simplicity
    // In a larger app, this would typically be in a separate Models folder
    public class UserProfile
    {
        public string Name { get; set; } = ""; // Initialize to empty string
        public int Age { get; set; } // int defaults to 0
        public string Gender { get; set; } = ""; // Initialize to empty string
        public bool IsSubscribed { get; set; } = false; // Initialize to false
    }
}
        

Key elements in the code:

  • UserProfile Class: A simple C# class to represent our form data, with properties for Name, Age, Gender, and IsSubscribed.
  • @bind on various inputs: Demonstrates two-way binding for <input type="text">, <input type="number">, <select>, and <input type="checkbox">.
  • @bind:event="oninput" on Name: This ensures the Name field updates the user.Name property (and thus the preview) on every keystroke, rather than just when the input loses focus.
  • @if (showPreview): This is Blazor's conditional rendering. The entire <div class="preview-box"> will only be rendered in the HTML if showPreview is true.
  • TogglePreview() method: Toggles the showPreview boolean, triggering a re-render of the component and thus showing or hiding the preview.
  • Ternary operator in button text: @(showPreview ? "Hide Preview" : "Show Preview") dynamically changes the button text based on the showPreview state.

๐Ÿงช Try this:

  • Run your Blazor application.
  • Navigate to /profile-form.
  • Fill out each field in the form (Name, Age, Gender, Checkbox).
  • Click the "Show Preview" button.
  • Experiment with clearing fields, changing values, and toggling the preview visibility. Watch how the "Live Profile Preview" updates in real-time.

๐ŸŽฏ Expected Output:

You will see an input form. As you type into the "Name" field, the "Live Profile Preview" (once shown) will update instantly. Other fields like "Age" and "Gender" will update when you tab out or select an option. Toggling the button will make the entire "Live Profile Preview" box appear or disappear.

Live Profile Preview

Name: [Your Name Here]

Age: [Your Age Here]

Gender: [Your Gender Here]

Subscribed: [Yes/No]

๐Ÿง  Bonus Challenges:

  • Add a "Reset Form" button: Implement a button that, when clicked, resets all fields in the user object back to their initial default values (e.g., user = new UserProfile();).
  • Disable the preview button conditionally: Make the "Show Preview" button disabled if the "Name" or "Gender" fields are empty. This introduces simple validation logic before showing the preview.
  • Observe @bind:event difference: Notice how the "Age" field (without @bind:event="oninput") only updates the preview when you click outside the input box, compared to "Name" which updates instantly.

Ready for Exercise 5: Events and EventCallbacks in Parent-Child components with interactivity? It’ll show how child components can trigger actions in a parent, just like a "Save Profile" button in a reusable form component.

Raushan Ranjan

Microsoft Certified Trainer

.NET | Azure | Power Platform | WPF | Qt/QML Developer

Power BI Developer | Data Analyst

๐Ÿ“ž +91 82858 62455
๐ŸŒ raushanranjan.azurewebsites.net
๐Ÿ”— linkedin.com/in/raushanranjan

Comments

Popular posts from this blog

Blazor: Building Web Apps with C# - Introduction

Blazor WebAssembly Hosted App Tutorial: Envelope Tracker System

Securing MVC-based Applications Using Blazor