ASP NET Core Blazor | Razor Component

ASP NET Core Blazor | Razor Component

When we create an Blazor app with Web Server Template then Components:

1. By default, there are three main pages Home, Counter, and FetchData. These pages are the component files Index.razor, Counter.razor, FetchData.razor.
yes .razor extension indicates that these are the razor components. We can also call them Blazor Component as well.

I strongly recommend you to watch the previous video/post before proceeding.
What is ASP.NET Blazor app?

On counter page, click me button is used to increase the counter without page reload. increment counter in webpage normally requires javascript or jQuery but with blazor, you can write c# code.

let have a look of the counter component.
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}

The HTML markup and C# code rendering logic are converted into a component class at build/compile time and the name of the generated .NET class matches the file name.

component class members are defined in @code{} block. Component state (properties, fields) and methods are specified for event handling or for defining and rendering other component logic.

Run the application to see these in Action.

When the Click me button is selected:

The Counter component's registered onclick handler is called (the IncrementCount method).
The Counter component regenerates its render tree.
The new render tree is compared to the previous one.
Only modifications to the Document Object Model (DOM) are applied.
The displayed count is updated.

Use components:
Add the Counter component to the app's Index component by adding a <Counter /> element to the Index component (Index.razor).

@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<Counter />

rebuild the app, and now index has its own counter. Yeah!

Click below to see the full video steps in Action.

No comments:

Post a Comment

Your feedback is important.
Visit www.techwebdots.in