如何在asp.net mvc中更改搜索viewLocation的顺序?

时间:2018-04-29 15:23:14

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

在我的项目中,我有一个名为Common的文件夹,我希望Asp.net Mvc搜索Common文件夹以查找Views,而不是share文件夹。

换句话说,搜索位置视图的顺序如下:

~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Common/Index.cshtml
~/Views/Common/Index.vbhtml

2 个答案:

答案 0 :(得分:2)

您可以创建自定义类继承RazorViewEngine

usin System.Web.Mvc
namespace Views.Infrastructure{
public class CustomrazorViewEngine : RazorViewEngin{
    public CustomrazorViewEngine(){
        ViewLocationFormats=new string[]{
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Common/{0}.cshtml"
            };
        }
    }
}

和Global.asax

proteced void Application_Start()
{
    AreaRegisteration.registerAllArea();
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new CustomrazorViewEngine());
    RoutConfig.registerRoutes(RouteTable.Routes);
}

我建议这样做是为了防止其他Viewengines的Confilict:

ViewEngines.Engines.Clear();

答案 1 :(得分:1)

一个简单的解决方案。

Application_Start事件上

通过RazorViewEngine收集获取ViewEngines.Engines并更新其ViewLocationFormats

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();
    razorEngine.ViewLocationFormats = new string[]
        {
            "~/Views/Home/Index.cshtml",
            "~/Views/Home/Index.vbhtml",
            "~/Views/Common/{0}.cshtml",
            "~/Views/Common/{0}.vbhtml"
        };
}

如果您只想更改订单,可以使用Concat方法合并defalut位置和新位置。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().First();

    var newLocationPath = new string[]
    {
        "~/Views/Home/Index.cshtml",
        "~/Views/Home/Index.vbhtml",
        "~/Views/Common/{0}.cshtml",
        "~/Views/Common/{0}.vbhtml"
    }.Concat(razorEngine.ViewLocationFormats);

    razorEngine.ViewLocationFormats = newLocationPath.ToArray();
}