【发布时间】:2012-03-08 08:11:34
【问题描述】:
我正在试用新的 ASP.NET MVC 4 移动功能。我用一个控制器(HomeController)和一个视图(Index)做了一个简单的应用程序。我还添加了索引视图的移动版本。
Views/Home/Index.cshtml
Views/Home/Index.Mobile.cshtml
在桌面浏览器中启动应用程序时,常规视图会按预期显示,但是当我作为三星 Galaxy S 在Opera Mobile Emulator 中启动应用程序时,我仍然看到常规视图而不是移动版本。
模拟器发送的用户代理字符串如下所示:
Opera/9.80 (Windows NT 6.1; Opera Mobi/23731; U; en) Presto/2.9.201 Version/11.50
关于为什么这不起作用的任何想法?
更新 感谢@nemesv,我能够解决这个问题,这是我目前的解决方案,希望它能涵盖大多数移动场景。
public class MobileDisplayMode : DefaultDisplayMode
{
private readonly StringCollection _useragenStringPartialIdentifiers = new StringCollection
{
"Android",
"Mobile",
"Opera Mobi",
"Samsung",
"HTC",
"Nokia",
"Ericsson",
"SonyEricsson",
"iPhone"
};
public MobileDisplayMode() : base("Mobile")
{
ContextCondition = (context => IsMobile(context.GetOverriddenUserAgent()));
}
private bool IsMobile(string useragentString)
{
return _useragenStringPartialIdentifiers.Cast<string>()
.Any(val => useragentString.IndexOf(val, StringComparison.InvariantCultureIgnoreCase) >= 0);
}
}
还有我 Global.asax
DisplayModeProvider.Instance.Modes.Insert(0, new MobileDisplayMode());
【问题讨论】:
-
救命稻草。教程没有这么说,这实际上很愚蠢。从微软的角度来看,它只是感觉很糟糕。他们的教程通常很到位。
-
谢谢,尽管 StringCollection 似乎是有史以来最没用的类之一。它不仅在此代码示例中没有提供任何内容,也没有提供性能,而且您必须编写额外的代码 (Cast
) 才能使用它。将其替换为 List 并从此过上幸福的生活
标签: asp.net-mvc-4