Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

asp.net - Is it possible to access MVC Views located in another project?

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();
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...