Asp.net mvc Asp.Net MVC更改DisplayModeProvider的视图位置

Asp.net mvc Asp.Net MVC更改DisplayModeProvider的视图位置,asp.net-mvc,asp.net-mvc-4,jquery-mobile,razor,Asp.net Mvc,Asp.net Mvc 4,Jquery Mobile,Razor,我开发了具有大量视图的大规模web应用程序。将桌面/移动视图放在同一个文件夹中很麻烦。是否可以将移动视图(name.mobile.cshtml)分组到显式子文件夹中,并告诉DisplayModeProvider在其中查找视图? 比如说, Views/Home/Index.Mobile.cshtml移动到Views/Home/Mobile/Index.Mobile.cshtml Views/People/List.Mobile.cshtml移动到Views/People/Mobile/List.M

我开发了具有大量视图的大规模web应用程序。将桌面/移动视图放在同一个文件夹中很麻烦。是否可以将移动视图(name.mobile.cshtml)分组到显式子文件夹中,并告诉DisplayModeProvider在其中查找视图? 比如说,

Views/Home/Index.Mobile.cshtml
移动到
Views/Home/Mobile/Index.Mobile.cshtml

Views/People/List.Mobile.cshtml
移动到
Views/People/Mobile/List.Mobile.cshtml

我找到了一些解决这个问题的方法

  • 我可以实现自定义RazorViewEngine(WebFormViewEngine)并指定自己的
    ViewLocationFormats
    集合

  • 我可以使用区域来实现这种行为

  • 我可以实现自定义的DefaultDisplayMode并重写
    TransformPath()
    方法来更改视图位置

  • 我认为第三种方法更简单。代码如下:

    首先,我创建自定义显示模式并从DefaultDisplayMode继承它:

    public class NewDisplayMode : DefaultDisplayMode
    {
        public NewDisplayMode()
            : base("Mobile") //any folder name you like, or you can pass it through parameter
        {
    
        }
    
        public NewDisplayMode(string folderName)
            : base(folderName) //any folder name you like, or you can pass it through parameter
        {
    
        }
    
        protected override string TransformPath(string virtualPath, string suffix)
        {
            string view = Path.GetFileName(virtualPath);
            string pathToView = Path.GetDirectoryName(virtualPath);
            virtualPath = (pathToView + "\\" + suffix + "\\" + view).Replace("\\", "/");
    
            return virtualPath;
        }
    }
    
    在上面的代码中,我覆盖
    TransformPath()
    方法和transform
    virtualPath
    字符串,以将位置更改为视图

    接下来,我只需要将此模式添加到模式集合:

    protected void Application_Start()
        {
            DisplayModeProvider.Instance.Modes.RemoveAt(0);
            DisplayModeProvider.Instance.Modes.Insert(0, new NewDisplayMode()
            {
                ContextCondition = context => context.GetOverriddenBrowser().IsMobileDevice
                //ContextCondition = context => context.Request.Url.Host == "www.m.mysite.com"
            });
            //other code
        }
    
    因此,我不需要重命名我的视图文件,我对移动视图和桌面视图使用相同的名称。最后,我的文件夹结构如下所示:


    非常好的帖子,谢谢。但是,使用上面的示例代码,“我的视图引擎”仍然在查找/Views/Home/Mobile/Index.Mobile.cshtml,而不是/Views/Home/Mobile/Index.cshtml-您知道可能有什么问题吗?