I want to separate my MVC project into several projects
So first of all, I've created two projects Front and Views
The Front project is a web application that contains controllers and models
The Views project is a class library project that will contains only the views
My question is how can I make controllers call views located in the Views project
I have controllers like this one:
public ActionResult Default() { return this.View(); }
Yes. Mention the view full path in the View method. If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter.
The main difference between ASP.NET Core and ASP.NET MVC 5 is their cross-platform approach. ASP.NET Core can be used on Windows, Mac, or Linux, whereas ASP.NET MVC 5 can only be used for applications on Windows.
If a view isn't found in this location, then by convention the MVC runtime looks in the “Views\Shared”. This simple organization scheme works well for small projects, but can become quite unwieldy as the size of the web site grows and the shared folder becomes an ever larger dumping ground.
For including controllers you need to change your route registrations to tell them where to look for the controllers:
routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", namespaces: new[] {"[Namespace of the Project that contains your controllers]"}, defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional});
For including views, create custom ViewEngine
:
public class CustomViewEngine: RazorViewEngine { public CustomViewEngine() { MasterLocationFormats = new string[] { "~/bin/Views/{1}/{0}.cshtml", "~/bin/Views/{1}/{0}.vbhtml", "~/bin/Views/Shared/{0}.cshtml", "~/bin/Views/Shared/{0}.vbhtml" }; ViewLocationFormats = new string[] { "~/bin/Areas/{2}/Views/{1}/{0}.cshtml", "~/bin/Areas/{2}/Views/{1}/{0}.vbhtml", "~/bin/Areas/{2}/Views/Shared/{0}.cshtml", "~/bin/Areas/{2}/Views/Shared/{0}.vbhtml" }; . . . } } protected void Application_Start() { ViewEngines.Engines.Add(new CustomViewEngine());
For more information look at the default implementation of RazorViewEngin
.
Here some good articles:
A Custom View Engine with Dynamic View Location
Using controllers from an external assembly in ASP.NET Web API
How to call controllers in external assemblies in an ASP.NET MVC application
How do I implement a custom RazorViewEngine to find views in non-standard locations?
Views in separate assemblies in ASP.NET MVC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With