我正在尝试新的ASP.NET MVC 4移动功能。我用一个控制器(HomeController)和一个视图(Index)做了一个简单的应用程序。我还添加了索引视图的移动版本。ASP.NET MVC 4移动功能
Views/Home/Index.cshtml
Views/Home/Index.Mobile.cshtml
当启动在桌面浏览器应用程序的常规示意图如图预期,但是当我启动在Opera Mobile Emulator作为三星Galaxy S的应用,我仍然得到常规视图,而不是移动版本。
从仿真器发送的用户代理字符串看起来是这样的:
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());
拯救生命。它真的很愚蠢,教程不会说这个。它只是从微软方面感觉如此半屁股。他们通常与他们的教程保持一致。 – 2012-09-20 14:29:40
谢谢,虽然StringCollection似乎是有史以来最无用的类之一。它不仅没有提供这个代码示例中的任何内容,也不提供性能,因此您不得不编写额外的代码(Cast),以便使用它。用替换它,然后快乐地生活 –
PandaWood
2014-09-30 07:03:51