在MVC 3中的多个位置搜索.cshtml?

Jac*_* M. 5 c# razor asp.net-mvc-3

当用户访问我的网站时,可能会template=foo在查询字符串中传递.该值正在验证并存储在Session.

我的文件布局如下所示:

- Views/
  - Templates/
    - test1/
      - Home
        - Index.cshtml
    - test2/
      - Home
        - List.cshtml
  - Home/
    - Index.cshtml
Run Code Online (Sandbox Code Playgroud)

基本上,如果用户请求Indextemplate=test1,我想用Views/Templates/test1/Index.cshtml.如果他们有template=test2,我想使用Views/Home/Index.cshtml(因为/Views/Templates/test2/Home/Index.cshtml不存在).如果他们没有通过模板,那么它应该直接进入Views/Home.

我是MVC和.NET的新手,所以我不知道从哪里开始寻找.我正在使用MVC3和Razor作为视图引擎.

Dan*_*eny 1

您可以通过创建自定义 RazorViewEngine 并设置ViewLocationFormats属性来完成此操作。这里有一个示例,它通过覆盖 来完成此操作WebFormViewEngine,但使用RazorViewEngine应该同样有效:

public class CustomViewEngine : WebFormViewEngine
{
    public CustomViewEngine()
    {
        var viewLocations =  new[] {  
            "~/Views/{1}/{0}.aspx",  
            "~/Views/{1}/{0}.ascx",  
            "~/Views/Shared/{0}.aspx",  
            "~/Views/Shared/{0}.ascx",  
            "~/AnotherPath/Views/{0}.ascx"
            // etc
        };

        this.PartialViewLocationFormats = viewLocations;
        this.ViewLocationFormats = viewLocations;
    }
}
Run Code Online (Sandbox Code Playgroud)