Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

blazor

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?

like image 939
rabejens Avatar asked May 13 '19 11:05

rabejens


People also ask

How do you make Blazor components?

To add a component to the project, right-click on the Pages folder and choose Add -> Razor Component. Refer to the following image. In the Add New Item- Blazor App dialog, provide the name EmployeeCard and click Add. Syncfusion's Blazor components suite is the expert's choice for building modern web apps.

How do I create components in Blazor dynamically?

Components in Blazor are formally referred to as Razor components. You can render the component at runtime using RenderFragment. The RenderFragment class allows you create the required content or component in a dynamic manner at runtime.

How do I render a component in Blazor?

To force a component to rerender, use the “StateHasChanged” method in Blazor, to notify that the state has been changed and requires re-rendering.


2 Answers

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.

like image 86
Knelis Avatar answered Nov 17 '22 01:11

Knelis


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

Currently, 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

like image 42
JOSEFtw Avatar answered Nov 17 '22 01:11

JOSEFtw