Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
sparrows81 Avatar asked Mar 24 '23 19:03

sparrows81


1 Answers

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

like image 100
Krishna Avatar answered Apr 25 '23 01:04

Krishna