rabejens
rabejens

Reputation: 8142

How to create "Code Behind" Blazor Components with VS 2019?

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?

Upvotes: 12

Views: 13844

Answers (4)

M.Hassan
M.Hassan

Reputation: 11032

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 does not inherit from ComponentBase and that will need to be resolved.

Upvotes: 6

Knelis
Knelis

Reputation: 7149

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.

Upvotes: 22

JOSEFtw
JOSEFtw

Reputation: 10091

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

Upvotes: 8

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

enter image description here

Upvotes: 9

Related Questions