sparrows81
sparrows81

Reputation: 431

Change master page if device is mobile in asp.net web form app

When you create a new asp.net project in Visual Studio 2012 it adds an ascx with this code:

// Determine current view

var isMobile = WebFormsFriendlyUrlResolver.IsMobileView(new HttpContextWrapper(Context));
CurrentView = isMobile ? "Mobile" : "Desktop";

// Determine alternate view
AlternateView = isMobile ? "Desktop" : "Mobile";

// Create switch URL from the route, e.g. ~/__FriendlyUrls_SwitchView/Mobile?ReturnUrl=/Page
var switchViewRouteName = "AspNet.FriendlyUrls.SwitchView";
var switchViewRoute = RouteTable.Routes[switchViewRouteName];
if (switchViewRoute == null)
{
     // Friendly URLs is not enabled or the name of the swith view route is out of sync
     this.Visible = false;
    return;
}
var url = GetRouteUrl(switchViewRouteName, new { view = AlternateView });
url += "?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl);
SwitchUrl = url;

I really don't understand how this works? What is this strange code?WebFormsFriendlyUrlResolver? I have an existing project and I want to know if it is possible to switch the master page if a mobile browser is detected?

Upvotes: 4

Views: 20359

Answers (2)

Krishna
Krishna

Reputation: 2481

WebFormsFriendlyUrlResolver is a helper class to fetch route association. It can be used if you want to enable friendly urls i.e. www.yourdomain.com/myaccount.aspx can be shown as www.yourdomain.com/Account

You dont need to use this (for your specific problem), however it is a cool feature of asp.net and is made easy by creating custom routes in the RouteTables

This article by Scott helped me understand friendly URLS

Now to your problem, changing the master page for a mobile device. The master page can only be changed in the pre-init event of a page. I dont know another means to inject a new master page after that, as I believe it is too late

When you have many pages, hook this handler to httpcontext

Below is a pseudo code that needs refining to your needs

void page_PreInit(object sender, EventArgs e)
    {
        Page p = this.Context.Handler as Page;
        if (p != null)
        {
            // set master page
            if(Request.Browser.IsMobileDevice){
              p.MasterPageFile = "~/MasterPages/mobile.master";
            }
            else{
               p.MasterPageFile = "~/MasterPages/normal.master";
            }

        }
    } 

Once you have figured this out, ensure you read this solution at SO which mentions building master pages for mobile devices

Upvotes: 6

Eduardo
Eduardo

Reputation: 182

To include code to Switch between Mobile and Desktop versions you must include, at the beginning of the page:

<%@ Register Src="~/ViewSwitcher.ascx" TagPrefix="friendlyUrls" TagName="ViewSwitcher" %>

Then include the View Switcher Control in your page:

<friendlyUrls:ViewSwitcher ID="ViewSwitcher1" runat="server" />

This control automatically switches the page's Master Page from Site.Master to Site.Mobile.Master

And don't forget to complete Page_Load on ViewSwitcher.ascx.vb. This is the code:

 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Determine current view
    Dim isMobile = WebFormsFriendlyUrlResolver.IsMobileView(New HttpContextWrapper(Context))
    CurrentView = If(isMobile, "Mobile", "Desktop")

    ' Determine alternate view
    AlternateView = If(isMobile, "Desktop", "Mobile")

    Dim strSwitchViewRouteName As String = "AspNet.FriendlyUrls.SwitchView"
    Dim SwitchViewRoute = RouteTable.Routes(strSwitchViewRouteName)
    If SwitchViewRoute Is Nothing Then
        ' Friendly URLs is not enabled or the name of the switch view route is out of sync
        Me.Visible = False
        Return
    End If
    ' Create switch URL from the route, e.g. ~/__FriendlyUrls_SwitchView/Mobile?ReturnUrl=/Page
    Dim url = GetRouteUrl(strSwitchViewRouteName, New With { _
        Key .view = AlternateView, .__FriendlyUrls_SwitchViews = True _
    })
    url += "?ReturnUrl=" & HttpUtility.UrlEncode(Request.RawUrl)
    SwitchUrl = url
End Sub

One final note... ViewSwitcher automatically changes me.MasterPageFile. For example if your form use the MasterPage "~/MyMasterPage.Master" the library searches for "~/MyMasterPage.Mobile.Master"; if the file is present, the library will automatically replace your form master page with: "~/MyMasterPage.Mobile.Master"

Please note that you must use an absolute address for your MasterPageFile. This is valid: "~/MyMasterpage.Master" and this will show an error message generated from the library: "MyMasterPage.Master"

<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/MyMasterpage.Master" AutoEventWireup="true" CodeBehind="Default.aspx.vb" nherits="Test._Default" %>

Upvotes: 1

Related Questions