Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Partial Class to a component in Blazor in Visual Studio 2019?

I'm not finding where should I click to create a partial class in visual studio 2019.

After I create a new "Razor Component" file, I can't add the partial class to it.

Where do I add it?

like image 378
Vencovsky Avatar asked Mar 05 '20 17:03

Vencovsky


People also ask

How do I add a partial class in Visual Studio?

Open Visual Studio from "Start" -> "All programs" -> "Microsoft Visual Studio". Then, go to "File" -> "New" -> "Project..." then select "Visual C#" -> "Windows" -> "Console application". Then, specify the name such as Partial class or whatever name you wish and the location of the project and click on the "OK" button.

How do you add 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.


2 Answers

There are two ways to add code behind to Razor component:

  1. Add Base class and in component add @inherits this class, how is described in this answer. In this case base class shouldn't be partial.

  2. Since October 2019 we can use partial classes. You can just add class name with the same name, adding .cs extension, mark it as partial class:

enter image description here

And you don't need to use @inherits in this case.

See Partial class support doc.

like image 76
Alexan Avatar answered Nov 14 '22 23:11

Alexan


Something like this? : - razor page with "code-behind" class

enter image description here

like image 32
yob Avatar answered Nov 14 '22 22:11

yob