use*_*616 3 asp.net-mvc razor jquery-mobile asp.net-mvc-4
我开发了具有很多视图的大型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集合。
我可以使用Areas实现此行为。
我可以实现自定义DefaultDisplayMode和重写TransformPath()方法来更改视图位置。
我认为第三种方式更简便。这是代码:
首先,我创建自定义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;
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我重写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
}
Run Code Online (Sandbox Code Playgroud)
因此,我不需要重命名视图文件,移动和桌面视图使用相同的名称。最后,我的文件夹结构如下所示:

| 归档时间: |
|
| 查看次数: |
1210 次 |
| 最近记录: |