我在web.config中有一个简单的配置开关,可以在使用移动版和桌面版应用之间切换。这是一个bool旗帜。然后在Global.asax文件中,我有以下代码:
private void ConfigureMobileViewSwitcher()
{
if(ConfigurationManager.AppSettings.Get("Mobile") != null)
{
bool isMobile = Convert.ToBoolean(ConfigurationManager.AppSettings["Mobile"]);
// only inject the mobile display mode if the switch is set in app settings
if (isMobile)
{
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Mobile")
{
ContextCondition = (context => isMobile)
});
}
}
}
问题在于,当移动开关为真时表示使用.Mobile页面并且移动页面不存在则会抛出错误而不是切换到同一视图的桌面版本。
The following sections have been defined but have not been rendered for the layout page
简单英语解释:
基本上我想要的是,如果某些操作不存在移动视图,那么它将呈现该视图的桌面版本。
更新:
我检查了DisplayModeProvider.Instance.Modes集合,在初始启动时它包含2个条目。
Index 0 has "Mobile
Index 1 has "" which I believe is the default
Then I insert another "Mobile" on Index 0
下面的屏幕截图显示了更多详细信息。
以下是实际错误:
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/MainLayout.cshtml": "head; breadcrumb; banner; leftContent; mainContent"
当我尝试在移动设备中查看页面并且该页面/视图不存在时,我收到上述消息。但是桌面应用程序存在该页面,移动应用程序应该回退到桌面视图。
答案 0 :(得分:0)
如果您配置了两种显示模式,这应该可以使用。首先,带有空后缀的DefaultDisplayMode将触发桌面视图(Index.cshtml)的显示,然后是第二个自定义移动显示模式,它将使用移动视图覆盖桌面视图(如果存在)(Index.Mobile) .cshtml)。如果移动视图不存在,它将回退到使用桌面视图。
public class CustomMobileDisplayMode : DefaultDisplayMode
{
public CustomMobileDisplayMode() : base("Mobile")
{
ContextCondition = httpContext => IsCustomMobile(httpContext);
}
private bool IsCustomMobile(HttpContextBase httpContext)
{
// All mobile devices will trigger the Mobile view
// Or, if the override setting is in the config
return httpContext.Request.Browser.IsMobileDevice ||
Convert.ToBoolean(ConfigurationManager.AppSettings["Mobile"]);
}
}
在某些地方,在配置期间,执行以下内容,这将初始化两种显示模式并以正确的顺序添加它们。
DisplayModeProvider.Instance.Modes.Clear();
DisplayModeProvider.Instance.Modes.Add(new DefaultDisplayMode());
DisplayModeProvider.Instance.Modes.Add(new CustomMobileDisplayMode());