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

时间:2011-06-22 21:21:05

标签: c# asp.net-mvc-3 razor

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

我的文件布局如下:

- Views/
  - Templates/
    - test1/
      - Home
        - Index.cshtml
    - test2/
      - Home
        - List.cshtml
  - Home/
    - Index.cshtml

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

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

2 个答案:

答案 0 :(得分:1)

您可以修改Scott Hanselman's Mobile Device demo以满足您的需求。您可以将逻辑放在检查查询字符串或会话变量中,而不是检查用户代理或是否是移动设备。

答案 1 :(得分:1)

您可以通过创建自定义RazorViewEngine并设置ViewLocationFormats属性来完成此操作。 There's a sample here通过覆盖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;
    }
}