我可以指定一个自定义位置来“搜索视图"吗?在 ASP.NET MVC 中? [英] Can I specify a custom location to "search for views" in ASP.NET MVC?

查看:27
本文介绍了我可以指定一个自定义位置来“搜索视图"吗?在 ASP.NET MVC 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 mvc 项目具有以下布局:

I have the following layout for my mvc project:

  • /控制器
    • /演示
    • /Demo/DemoArea1Controller
    • /Demo/DemoArea2Controller
    • 等等...
    • /演示
    • /Demo/DemoArea1/Index.aspx
    • /Demo/DemoArea2/Index.aspx

    但是,当我为 DemoArea1Controller 设置这个时:

    However, when I have this for DemoArea1Controller:

    public class DemoArea1Controller : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
    

    我收到无法找到视图‘索引’或其主视图"错误,以及通常的搜索位置.

    I get the "The view 'index' or its master could not be found" error, with the usual search locations.

    如何在Demo"视图子文件夹中的Demo"命名空间搜索中指定控制器?

    How can I specify that controllers in the "Demo" namespace search in the "Demo" view subfolder?

    推荐答案

    您可以轻松扩展 WebFormViewEngine 以指定要查找的所有位置:

    You can easily extend the WebFormViewEngine to specify all the locations you want to look in:

    public class CustomViewEngine : WebFormViewEngine
    {
        public CustomViewEngine()
        {
            var viewLocations =  new[] {  
                "~/Views/{1}/{0}.aspx",  
                "~/Views/{1}/{0}.ascx",  
                "~/Views/Shared/{0}.aspx",  
                "~/Views/Shared/{0}.ascx",  
                "~/AnotherPath/Views/{0}.ascx"
                // etc
            };
    
            this.PartialViewLocationFormats = viewLocations;
            this.ViewLocationFormats = viewLocations;
        }
    }
    

    确保您记得通过修改 Global.asax.cs 中的 Application_Start 方法来注册视图引擎

    Make sure you remember to register the view engine by modifying the Application_Start method in your Global.asax.cs

    protected void Application_Start()
    {
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new CustomViewEngine());
    }
    

    这篇关于我可以指定一个自定义位置来“搜索视图"吗?在 ASP.NET MVC 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆