可以在自定义View Engine中动态修改布局视图值吗?

时间:2012-05-31 14:57:45

标签: asp.net-mvc-3 razor

目前我有一个自定义视图引擎,它将检测应用程序配置文件中的设置,并相应地将一个字符串附加到视图文件的末尾。以状态为例,如果它检测到Vermont,它会将"_VT"附加到View文件名的末尾。它工作正常,如果没有找到"_VT",则默认为文件而没有任何特殊结尾。

在我的Razor视图中,我可以使用Layout = ""选项为视图指定布局。我的问题是,有没有一种方法可以像在View Engine中那样对布局做类似的事情?基本上,如果在配置中检测到Vermont,请将"_VT"添加到布局视图文件名。

当前视图引擎:

public class PlanSpecificRazorViewEngine : RazorViewEngine
{
    public PlanSpecificRazorViewEngine()
    {
        ViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
        PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
        AreaViewLocationFormats = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{1}/Views/Shared/{0}.cshtml" };
        AreaPartialViewLocationFormats = new [] {"~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" };
    }

    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        string Plan = System.Configuration.ConfigurationManager.AppSettings["Plan"];
        return base.FindView(controllerContext, viewName + "_" + Plan, masterName, useCache);
    }

    public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
    {
        string Plan = System.Configuration.ConfigurationManager.AppSettings["Plan"];
        return base.FindPartialView(controllerContext, partialViewName + "_" + Plan, useCache);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在构造函数中设置默认MasterLocationFormats

public PlanSpecificRazorViewEngine()
{
    ...

    string Plan = System.Configuration.ConfigurationManager.AppSettings["Plan"];
    MasterLocationFormats = new string[] 
    { 
        "~/Views/Shared/{0}_" + Plan + ".cshtml",
        "~/Views/Shared/{0}_" + Plan + ".vbhtml"
    };
}