Is it possible to access MVC Views located in another project?

前端 未结 3 1568
刺人心
刺人心 2020-11-27 13:16

I want to separate my MVC project into several projects

So first of all, I\'ve created two projects Front and Views

The

3条回答
  •  天命终不由人
    2020-11-27 14:00

    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 View you 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

提交回复
热议问题