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

时间:2014-10-21 13:48:02

标签: 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.Mobile.cshtml

1 个答案:

答案 0 :(得分:5)

好吧,我找到了解决这个问题的方法。

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

  2. 我可以使用区域来实现此行为。

  3. 我可以实现自定义DefaultDisplayMode并覆盖TransformPath()方法来更改视图位置。

  4. 我认为第三种方式更简单方便。这是代码:

    首先我创建自定义DisplayMode并从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()方法并转换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
        }
    

    因此,我不需要重命名我的视图文件,我对移动和桌面视图使用相同的名称。最后,我的文件夹结构如下:

    enter image description here