Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share views (.cshtml files) between projects in asp.net core solution

I have a project which for various reasons have a number of controllers and views that are essentially the same. At the moment they are replicated between projects so there are several copies of each in each project. I was wondering if there was anyway to put these in a separate project (e.g. a class library project) and amend the View Locator capabilities (IViewLocationExpander?) or some other means to get it to look in a different project for these views.

I know it was possible in “full” asp.net with a bit of hacking about and it was never very clean or elegant, so wondered if there was any better way with asp.net core?

Thanks

like image 659
LDJ Avatar asked Feb 02 '17 09:02

LDJ


People also ask

Can one controller have multiple views?

You can / will absolutely have multiple Views from a Controller. Just think about creating a model for each view if you want to stick up with MVC pattern. Save this answer.

Can an action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.

Is Razor better than MVC?

From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.

Can you mix razor pages and MVC?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.


1 Answers

You could create a AspNetCore Class Library and use AspNetCore Precompiled Views. Also as indicated in this StackOverflow answer. That should allow you to compile and share the Controllers and Views as you want. The views (.cshtml files) would no longer need to be deployed as they would be compiled and available in this class library.

Then either add a reference to this class library project (if in the same solution) or create it as a Nuget package and add it to the other projects. (This can be done by a private Nuget server or Local Nuget repository folder).

Update: ASP.NET Core 2.1 has a new Razor SDK which makes this simpler. It emits a Views assembly (AppName.Views.dll).

like image 160
truemedia Avatar answered Oct 16 '22 03:10

truemedia