kosnkov
kosnkov

Reputation: 5941

Using partials in mvc from other project

Is that possible to move some partials (*.cshtml) to core classes project and use them in other mvc project ?

Maybe by injecting or using something in _ViewImports ?

Upvotes: 2

Views: 907

Answers (2)

Drew Brasher
Drew Brasher

Reputation: 838

You could put them in a Razor Class Library:

https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class

Razor views, pages, controllers, page models, Razor components, View components, and data models can be built into a Razor class library (RCL). The RCL can be packaged and reused. Applications can include the RCL and override the views and pages it contains. When a view, partial view, or Razor Page is found in both the web app and the RCL, the Razor markup (.cshtml file) in the web app takes precedence.

Create a class library containing Razor UI

  • From Visual Studio select Create new a new project.
  • Select Razor Class Library > Next.
  • Name the library (for example, "RazorClassLib"), > Create. To avoid a file name collision with the generated view library, ensure the
    library name doesn't end in .Views.
  • Select Support pages and views if you need to support views. By default, only Razor Pages are supported. Select Create.

The Razor class library (RCL) template defaults to Razor component development by default. The Support pages and views option supports pages and views.

Upvotes: 2

wserr
wserr

Reputation: 466

You can do this using Areas. You can find everything about them on the microsoft docs page.

The MVC project with the partial views that you want to use needs a structure like this (found on the microsoft docs page, see link above):

enter image description here

So let's say you want a partial view called _TestPartial.cshtml in the Area Home. Then you need the following structure:

enter image description here

Then, in the main project, you reference this new project you created.

Next, you need an extra endpoint in your startup.cs file:

app.UseEndpoints(endpoints =>
{
    endpoints.MapAreaControllerRoute(
        name: "Home",
        areaName: "Home",
        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Finally, you can use this Partial in your views like so:

<div>@await Html.PartialAsync("/Areas/Home/Views/Home/_TestPartial.cshtml")</div>

You can now also redirect to controller actions in these areas like this:

return RedirectToAction("Index","Home",new { area = "Home "});

Upvotes: 1

Related Questions