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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With