Group MVC3 views into sub-folders under main '

2020-06-19 04:19发布

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?

2条回答
够拽才男人
2楼-- · 2020-06-19 04:55

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

查看更多
迷人小祖宗
3楼-- · 2020-06-19 05:06

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());
查看更多
登录 后发表回答