如何在ASP.NET MVC中更改搜索视图的顺序



在我的项目中,我有一个名为 Common的文件夹,我想使用ASP.NET MVC搜索通用文件夹以查找视图,而不是共享文件夹。

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

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

您可以创建自定义类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的封锁:

ViewEngines.Engines.Clear();

一个简单的解决方案。

Application_Start事件上,通过ViewEngines.Engines收集RazorViewEngine并更新其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();
}

相关内容

  • 没有找到相关文章

最新更新