Reputation: 8142
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
Reputation: 11032
In Vs2019 v 16.8.4 using the experimintal Razor, a new option "Extract block to code behind"
The steps are:
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
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
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
Reputation: 20901
I don't like explaining ways by words but visualizing.
Upvotes: 9