2012-07-18 39 views
6

我正在尝试为平板电脑和手机制作单独的视图。在app_start我有这样的代码MVC 4手机和平板电脑视图分离

DisplayModeProvider.Instance.Modes.Insert(0, new 
     DefaultDisplayMode("Tablet") 
     { 
      ContextCondition = (ctx => 
      ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >= 0 || 
      ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0) 
     }); 

我已经创建了两个布局文件,一个用于手机和一个适用于平板电脑。但是当我通过Android上的移动设备访问时存在冲突。它将我重定向到layout.tablet。我怎么能分开这两个设备?

回答

8

我已经用浏览器中的用户代理切换器测试过了,它工作正常。

DisplayModeProvider.Instance.Modes.Insert(0, new 
     DefaultDisplayMode("Tablet") 
     { 
      ContextCondition = (ctx => 
      ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >= 0 || 
      ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0 && 
      ctx.Request.UserAgent.IndexOf("mobile", StringComparison.OrdinalIgnoreCase) < 1) 
     }); 

     DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Mobile") 
     { 
      ContextCondition = (ctx => 
       ctx.GetOverriddenBrowser().IsMobileDevice) 
     }); 
+0

嘿,宝贝,你让我的荣耀回归! :) – 2013-01-07 09:52:31

1

neowinian,

尝试增加逻辑的一个额外片段:

&& ctx.Request.UserAgent.IndexOf("mobile", StringComparison.OrdinalIgnoreCase) < 0 

这将排除您的DISPLAYMODE用于平板电脑所有的移动设备。

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Tablet") 
{ 
    ContextCondition = (ctx => 
    (ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >=0 
     || ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0) 
     && ctx.Request.UserAgent.IndexOf("mobile", StringComparison.OrdinalIgnoreCase) < 0) 
}); 

另外,你可以看看:

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Mobile") 
{ 
    ContextCondition = (ctx => 
     ctx.GetOverriddenBrowser().IsMobileDevice) 
}); 
0

你是否曾经看一个服务像http://51degrees.mobi做所有用户代理/设备繁重的工作吗?虽然它不是免费的,但他们会做一个“精简”版本,可以给你很多你需要的东西,但我注意到“IsTablet”是他们的高级版本。

+0

我试了一下,但MVC 4带有移动功能,对我来说非常整洁。 – jasenkoh 2012-07-18 12:22:16

0

您可以使用51Degrees的免费云端解决方案来帮助您检测不同的设备类型。使用IsMobile和IsTablet属性,可以根据结果重定向。您可以从网站获取免费云产品并获得免费云密钥。有关如何使用API​​的信息,请参阅此处的教程。 https://51degrees.com/Developers/Documentation/APIs/Cloud-API/NET-Cloud

例如,您可以请求返回类似于下面显示的设备类型,然后根据响应放入您的重定向逻辑。

@using (var webClient = new System.Net.WebClient()) 
{ 
    string json = webClient.DownloadString(String.Format(
    "https://cloud.51degrees.com/api/v1/{0}/match?user-agent= 
{1}&values=DeviceType", 
    "YOUR KEY HERE", 
    HttpUtility.UrlEncode(Request.UserAgent))); 

dynamic match = Newtonsoft.Json.Linq.JObject.Parse(json); 
    SortedList<string, string[]> values = Newtonsoft.Json.JsonConvert.DeserializeObject<SortedList<string, string[]>>(match.Values.ToString()); 
    string[] hvValues; 

if (values.TryGetValue("DeviceType", out hvValues)) 
    { 
foreach (string s in hvValues) 
{ 
<h4> 
    Device Type: 
    @s 
</h4> 
} 
    } 

披露:我在51Degrees工作。