如何让MVC最后在Views / Shared文件夹中查找razor和webforms视图?

时间:2011-09-13 03:35:10

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

我有一个较旧的ASP.NET MVC应用程序,它使用经典的Web表单视图。作为一项实验,我们已经开始混合一些剃刀视图。不幸的是,找到所需视图的默认优先级不是我想要的。 MVC首先在/ Views / ControllerName文件夹中查找aspx和ascx文件。然后它移动到/ Views / Shared for aspx和ascx文件。然后它开始寻找.cshtml和.vbhtml文件。我想要的是它不会进入共享文件夹,直到它耗尽/ Views / ControllerName文件夹中的所有可能性。我该怎么做?

---更新---

以下是一些可能有助于解释我所追求的内容的其他信息。默认情况下,我会收到此搜索顺序:

~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml 

我想要的是:

~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

换句话说,在完全搜索/ Views / ControllerName文件夹之前,它不应搜索Shared。

2 个答案:

答案 0 :(得分:3)

您可以在global.asax.cs文件中配置视图引擎的优先级

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());
        ViewEngines.Engines.Add(new WebFormViewEngine());
    }

答案 1 :(得分:0)

在玩了一下之后,我用一个简单的Fluent API就能达到我想要的效果。扩展方法从每个视图引擎中删除我不想要的搜索位置。搜索位置存储在.ViewLocationFormats.PartialViewLocationFormats字符串数组中。所以这里是一个流畅的API,可以从这些数组中删除不需要的项目:

public static class BuildManagerViewEngineFluentExtensions {
    public static BuildManagerViewEngine ControllerViews(this BuildManagerViewEngine engine) {
        return FilterViewLocations(engine, x => x.Contains("/Views/Shared/") == false);
    }

    public static BuildManagerViewEngine SharedViews(this BuildManagerViewEngine engine) {
        return FilterViewLocations(engine, x => x.Contains("/Views/Shared/") == true);
    }

    private static BuildManagerViewEngine FilterViewLocations(BuildManagerViewEngine engine, Func<string, bool> whereClause) {
        engine.ViewLocationFormats = engine.ViewLocationFormats.Where(whereClause).ToArray();
        engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Where(whereClause).ToArray();
        return engine;
    }
}

然后,在我的global.asax中,我将以下行添加到protected void Application_Start()

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine().ControllerViews());
ViewEngines.Engines.Add(new WebFormViewEngine().ControllerViews());
ViewEngines.Engines.Add(new RazorViewEngine().SharedViews());
ViewEngines.Engines.Add(new WebFormViewEngine().SharedViews());