修改asp.net mvc视图命名约定

时间:2011-01-29 02:03:13

标签: asp.net-mvc

在asp.net mvc 3中,View()方法将按照此命名约定选择要呈现的视图

\Views\Controller\Action.cshtml

如何修改命名约定,以便从以下位置返回视图:

\Views\Theme\Controller\Action.cshtml

Theme从Session

获得
var theme = Session["SelectedTheme"] ?? "Default";

这是当前的文件夹结构

- ...
-Controllers
 |-HomeController
 |-AccountController
- ...
-Views
 |-ThemeABC
    |-Home
    |-Account
 |-ThemeXYZ
    |-Home
    |-Account
 |-Default
    |-Home
    |-Account
- ...

1 个答案:

答案 0 :(得分:0)

我发现this post非常有帮助。从他的代码中,我只需要在构造函数中修改LocationFormats,如下所示。

public class AndraViewEngine : RazorViewEngine
{
    public AndraViewEngine()
    {
        base.ViewLocationFormats = new string[] { 
            "~/Views/{2}/{1}/{0}.cshtml", 
            "~/Views/{2}/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.cshtml", 
            "~/Views/Shared/{0}.cshtml"
        };

        base.PartialViewLocationFormats = new string[] {
            "~/Views/{2}/{1}/{0}.cshtml", 
            "~/Views/{2}/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.cshtml", 
            "~/Views/Shared/{0}.cshtml"
        };
    }

    /* the rest of the code in that post */
}