Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 mobile and tablet view separation

Tags:

c#

asp.net-mvc

I'm trying to make separate views for Tablet and Mobile. In app_start i have this code

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)
        });

I've created two layout files, one for mobile and one for Tablet. But there is conflict when i'm accessing from mobile device which is on Android. It redirects me to layout.tablet. How could i separate those two devices?

like image 738
jasenkoh Avatar asked Jul 18 '12 10:07

jasenkoh


2 Answers

I've tested this with user-agent switcher in browser and it works fine.

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)
        });
like image 109
jasenkoh Avatar answered Nov 02 '22 13:11

jasenkoh


neowinian,

Try adding one additional snippet of logic:

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

this will exclude all mobile devices from your DisplayMode for tablet.

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)
});

additionally, you could look at:

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Mobile")
{
    ContextCondition = (ctx =>
        ctx.GetOverriddenBrowser().IsMobileDevice)
});
like image 41
jim tollan Avatar answered Nov 02 '22 15:11

jim tollan