Hal Heinrich
Hal Heinrich

Reputation: 642

How do I convert a razor page with an injection to a code-behind?

I'm modifying a blazor example from [Blazor Tips and Tricks][1]

[1]: https://www.youtube.com/watch?v=3duXMxwnkXI starting at the 17 minute mark.

If you create a new Blazor App named BlazorCounter in Visual Studio, and modify the generated Counter.razor to look like this:

@page "/counter"
@inject Data.CounterState State

<h1>Counter</h1>

<p>Current count: @State.CurrentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {

    void IncrementCount()
    {
        State.CurrentCount++;
    }
}

Then add the following c# class to the Data folder namespace BlazorCounter.Data { public class CounterState { public int CurrentCount { get; set; } } } Finally add this line at the end of the ConfigureServices method of Startup class:

            services.AddScoped<CounterState>();

Then you have a counter which preserves its state and doesn't start at zero every time you navigate to the Counter page.

My question is: How do I convert this to 'code-behind' and separate the C# code? I've converted other razor pages to 'code-behind', but don't see how to handle the @inject line.

Upvotes: 2

Views: 1923

Answers (1)

itminus
itminus

Reputation: 25380

Create a Base class and inject the service with an [InjectAttribute]:

public class MyCounterComponent : ComponentBase
{

    [Inject]
    public virtual CounterState State { get; set; }

    protected void IncrementCount()
    {
        State.CurrentCount++;
    }
}

I also move your IncrementCount() method from the view file to this class file.

And now you can use it with a @inherits directive:

@page "/counter"
@inherits BlazorApp1.Pages.MyCounterComponent

<h1>Counter</h1>

<p>Current count: @State.CurrentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

For more details, see Request a service in a component and Use DI in services

Upvotes: 4

Related Questions