Group MVC3 views into sub-folders under main '

2020-06-19 04:56发布

问题:

E.g. I have three payment controllers, each specific to a third party payment processor, so under my root Views folder, I have one folder for each of these controllers. I would like to move these into Views\Payments\Processor1, Views\Payments\Processor2, etc. instead of the current Views\Processor1 etc.

I am not ready to implement areas yet, so I'm hoping there is some way I can tell MVC to also look in subfolders, or something like that. Can this be done and how?

回答1:

You could write a custom view engine and override the default view locations:

public class MyRazorViewEngine : RazorViewEngine
{
    public MyRazorViewEngine() : base()
    {
        base.ViewLocationFormats = base.ViewLocationFormats.Concat(new[] {
            "~/Views/Payments/{1}/{0}.cshtml",
            "~/Views/Payments/{1}/{0}.vbhtml"
        }).ToArray();

        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Concat(new[] {
            "~/Views/Payments/{1}/{0}.cshtml",
            "~/Views/Payments/{1}/{0}.vbhtml"
        }).ToArray();
    }
}

and then register it in Application_Start:

ViewEngines.Engines.Add(new MyRazorViewEngine());


回答2:

Do you need for the views to be searched for? You can specify which view to use in your View() call, complete with path.