Search code examples
asp.net-mvcasp.net-mvc-4viewprojectprojects-and-solutions

How to see all the views in mvc application


I added a default MvcApplication (MVC 4) (its name is MvcApplication3 matching the name of my solution's) width Home views (About, Index, Contact) and that will be my startup (bold in VS solution explorer's interface) project. Then I added another project (MvcApplication, but this time an empty one) called MvcApplication2 to the solution. Then I added the latter project as a reference to the first. I also added a controller called TestController (green line) to the referenced project and generated a view for its Index (red arrow) method. However, when I go to a link /Test or /Test/Index, the view I am expecting (red arrow) is not shown. Then I added the same folder Test with Index.cshtml (blue arrow) to the main project and now I am seeing its contents rather than the project's where my controller sits in.

Is it possible to make the application look for the views in the other project rather than the startup one?

I am adding the image of the structure to make it easier to follow.

P.S.: probably related: the breakpoint IS being hit in the Index method of TestController.

tldr; blue view is used instead of a red one

enter image description here


Solution

  • With some ideas from me and a friend of mine and a link about overriding RazorViewEngine I finally got what I wanted working exactly how I was expecting it to:

    1. I created a folder named ViewsBase in the main project.
    2. I rewrote RazorViewEngine this way: I only changed the place that was needed for me, leaving everything else like I found in the constructor of RazorViewEngine:

      public class MyCustomViewEngine : RazorViewEngine { public MyCustomViewEngine() { ...

           ViewLocationFormats = new[]
           {
                "~/Views/{1}/{0}.cshtml",
                "~/Views/{1}/{0}.vbhtml",
                "~/Views/Shared/{0}.cshtml",
                "~/Views/Shared/{0}.vbhtml",
                "~/ViewsBase/{1}/{0}.cshtml",
                "~/ViewsBase/{1}/{0}.vbhtml"
           };
      
          ...
      

    (I find it rather disturbing how I am unable to format the code properly. Can someone give me a hand please?)

    and in Global.asax of the main project I added:

    ViewEngines.Engines.Clear();
    var ourViewEngine = new 
    ViewEngines.Engines.Add(ourViewEngine);
    
    AreaRegistration.RegisterAllAreas();
    ...
    
    1. I added a post-build event command:

      xcopy /s "$(ProjectDir)Views\*.*" /Y "$(SolutionDir)$(SolutionName)\ViewsBase\"

    2. It started looking for the views in the expected order

    3. I added a ViewStart file to the base project to make it render the Layout too.