Exercise 2: Personalized Welcome Message (Blazor WebAssembly)

Exercise 2: Personalized Welcome Message (Blazor WebAssembly)

Exercise 2: Personalized Welcome Message (Blazor WebAssembly)

Goal: Create a reusable greeting component that can show different names depending on where it's used.

Concepts You'll See:

  • Creating a brand new Razor Component file.
  • Using [Parameter] to allow data to be passed into a component.
  • Using one component inside another.

Step-by-Step Instructions:

1. Continue from Exercise 1:

  • Open your MyFirstCounterApp project in Visual Studio if it's not already open.

2. Create a New Component File:

  • In "Solution Explorer" (on the right), right-click on the Pages folder.
  • Select "Add" -> "Razor Component...".
  • In the "Add New Item" dialog, type WelcomeMessage.razor as the name.
  • Click "Add".

A new empty file named WelcomeMessage.razor will open in your editor.

3. Write the WelcomeMessage Component Code:

Paste the following code into the WelcomeMessage.razor file, replacing anything that might already be there:

@* This is our reusable greeting component *@

<h3>Hello, @YourName! It's great to have you here.</h3>

@code {
    [Parameter] // This special tag tells Blazor that 'YourName' is something a parent can provide
    public string YourName { get; set; } = "Buddy"; // 'Buddy' is the default if no name is given
}

Save the file: Press Ctrl + S.

4. Use Your New Component in Index.razor (Your Home Page):

  • In "Solution Explorer," double-click on Index.razor (also in the Pages folder) to open it.
  • Find the line that says:
  • Welcome to your new app.
    
  • Below that line, add your WelcomeMessage component two times, showing different ways to use it:
  • @page "/"
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <WelcomeMessage YourName="Alice" /> @* Here, we pass the name "Alice" to the component *@
    
    <WelcomeMessage /> @* Here, we don't pass a name, so it will use the default "Buddy" *@
    

Save the file: Press Ctrl + S.

5. Run Your Application and Test:

  • Press F5 to run the application.
  • Your browser will open to the home page (/).

Observation: You should now see two greeting messages:

  • "Hello, Alice! It's great to have you here."
  • "Hello, Buddy! It's great to have you here."

Explanation: This shows how you can make flexible components that adapt based on the information (Parameters) you give them!

When you're done, close the browser and stop debugging (Shift+F5).

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