Renato Sanhueza
Renato Sanhueza

Reputation: 564

Sharing View Components across several projects

I have a fairly big view component that I want to use in two different asp.net core MVC projects. So far I found two approaches for accomplish this:

  1. Encapsulating it into a DLL
  2. Making a shared (dummy) web project

What are the trade-offs between these two approaches? My view component has nested view components and it requires java-script to implement some dynamic functionality.

Upvotes: 3

Views: 2378

Answers (1)

Xeevis
Xeevis

Reputation: 4521

With ASP.NET Core 2.1 onwards you want to use Razor Class Libraries (RCL) which were designed for this very scenario.

RLC lets you create reusable UI with razor views, pages, controllers, page models, view components and data models. Added benefit is that views (even partial) are overridable by main app where the Razor markup (.cshtml file) takes precedence allowing for per-app changes without modifying the original shared component.

  • From the Visual Studio File menu, select New > Project.
  • Select ASP.NET Core Web Application.
  • Name the library (for example, "RazorClassLib") > OK. To avoid a file name collision with the generated view library, ensure the library name doesn't end in .Views.
  • Verify ASP.NET Core 2.1 or later is selected.
  • Select Razor Class Library > OK.
  • Reference the RCL from main app (you can also make the shared library as NuGet package)
  • Start the application and visit /MyFeature/Page1

Read the full documentation

Upvotes: 5

Related Questions