When some logic in C# can be shared between projects, we gonna create a new class library project. But sometimes we just want to share some view components. For example, for all pages in Aiursoft
, it all contains a Logout
component. Writing this more than one time doesn't make sense. So how can we share it?
First, we gonna create a new .NET Core
class library project alongside it. Name it: Aiursoft.Pylon
.
Make sure your shared class library support razor. Modify your csproj
file to add the property:
<AddRazorSupportForMvc>true</AddRazorSupportForMvc>
Your class library project file shall be like:
Now your project Aiursoft.Pylon
supports writing the razor class library now. We can start writing a new view component.
Put all your view components under the: Views/Shared/Components
folder. To write a view component, please reference the document:
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components
When you finished writing your view component, your folder shall be like this:
Now your view component is done and can be shared between projects. Now create a new web project which references your class library.
Now we will import all view components from your class library to your new web project. Modify your _ViewImports.cshtml
to add the namespace like this:
Now you can use the shared view components in your views. Like this:
If your code is shown in dark green, then everything is fine and your view component can be run successfully.
Where do you think Razor Class Library fits in here? I want to share some views, controls & code between two AspNetCore 3.1 web apps but am put off by the initial RCL template which seemed intended for Blazor and not MVC.
My vc:simple tag is green, but I'm getting: A view component named 'Simple' could not be found.
Any ideas why I get this error?