11

I can create an inline component like

<h1>@foo</h1>

@functions {

    string foo = "foo";
}

However when I create Foo.razor containing just:

<h1>@foo</h1>

And Foo.razor.cs containing:

namespace MyApp.Client.Components {
    public class Foo: ComponentBase {

        public string foo;
    }
}

I get:

Error   CS0101  The namespace 'MyApp.Client.Components' already contains a definition for 'Foo'

I am using the latest VS 2019 and Blazor libraries.

What am I doing wrong?

rabejens
  • 7,594
  • 11
  • 56
  • 104

4 Answers4

17

Since October 2019, it is possible to use partial classes. So today you can name the class in the code-behind file like this:

public partial class Foo : ComponentBase
{
    protected override Task OnInitializedAsync()
    {
        // do stuff
    }
}

If you name the class file Foo.razor.cs it will appear under the Foo.razor razor file in solution explorer.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Knelis
  • 6,782
  • 2
  • 34
  • 54
  • 1
    If your class is generic you will need to add `@typeparam T` to the .razor file. –  May 08 '21 at 20:50
8

UPDATE: This is now possible: https://stackoverflow.com/a/59470941/1141089


Currently (May 13, 2019), the "code-behind" and .razor view can't share the same name.

So when you have Foo.razor.cs and Foo.razor it is seen as the same file and thus causes a collision.

Workaround for now: Rename your Foo.razor.cs to FooBase.cs (or something else).

Then in your Foo.razor, add @inherits FooBase

There is a GitHub issue regarding this here: https://github.com/aspnet/AspNetCore/issues/5487

JOSEFtw
  • 9,781
  • 9
  • 49
  • 67
8

I don't like explaining ways by words but visualizing.

enter image description here

5

In Vs2019 v 16.8.4 using the experimintal Razor, a new option "Extract block to code behind"

The steps are:

  • Enable expermintal Razor: Option->Environment -> Preview Featurs-> Enable expermintal Razor editor (need restart)
  • Put the cursor over @{code} or press Control + . //dot
  • Dropdown menu is displayed with "Extract block to code behind"
  • Click "Extract block to code behind"
  • Then Vs2019 extract the code in a new *.razor.cs file being created side-by-side e.g "Counter.razor.cs" for the counter.razor Component.

The generated class sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Lab2.Pages
{
    public partial class Counter
    {
        private int currentCount = 0;

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

Note: The generated partial class don't inherit from ComponentBase

M.Hassan
  • 10,282
  • 5
  • 65
  • 84