1
votes

I just started going through the Blazor tutorial, and am trying to get a grasp on the code. I have a razor page that looks like this (from the tutorial):

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

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

<!--
    This has been moved to the code-behind.
@code {
    private int currentCount = 0;

    private void IncrementCount() {
        currentCount++;
    }
}
-->

The code behind is giving me a couple of errors, saying Counter has already been defined and IncrementCount already exists. My code behind looks like this:

using Microsoft.AspNetCore.Components;

namespace BlazorApp8.Pages {

    public partial class CounterCode : ComponentBase {

        protected int currentCount = 0;

        protected void IncrementCount () {
            currentCount++;
        }


    }

}

I know I have done something simple wrong, but not sure what. Can someone assist?

2
Why do you need a partial class? - Circuit Breaker
I don't. That was me trying to figure out what I was doing. I had just left out a line of code (see answer below). - John

2 Answers

0
votes

I got it. In your client-side code, you must inherit from your class, like this:

@inherits CounterCode   <!-- This is what I missed -->
@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

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

I prefer the other way to create a code behind file.

Create a new class file Counter.razor.cs within the same directory. Add partial to the class. Done!