1

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?

John
  • 185
  • 1
  • 3
  • 17

2 Answers2

0

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>
John
  • 185
  • 1
  • 3
  • 17
  • Hi Brian, just a note to look into for later; The partial class approach can work well, but you might have some issues if you get into Generic Components and more complex scenarios. In those cases, set up a base class as the code behind (not partial), then inherit that base class in the razor file. Hope this helps, good luck! – Nik P May 12 '20 at 18:55
  • Good info. Thanks, Nik! This is new and exciting. – John May 13 '20 at 12:24
0

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!

Marvin Klein
  • 1,436
  • 10
  • 33