0

I'm looking for some advice for the best way to do this.

Basically I have some javascript that detects if the user is on a mobile device, if they are a css file is loaded, a mobile class is added to the page's body, and a hidden field is given a value of mobile. Then I check the value of this hidden field so I can run methods specific to mobile devices.

Currently I have everything working as desired but I'm forced to do a javascript postback on the first page load so the the hidden field's value can be accessed from the code behind. I'm just wondering if there's a better way to do this?

Here's a bit of my code.

    if ( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
     $("body").addClass("mobile");
     $('head').append('<link rel="stylesheet" href="Styles/mobile.css" type="text/css" />');
     $('head').append('<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0;">');
     if ($("#hfdevice").val() != "mobile")
     {
          $("#hfdevice").val("mobile");
          __doPostBack('hfdevice','');
     }
   }

.

HiddenField hfdevice = (HiddenField)Master.FindControl("hfdevice");
     if (hfdevice.Value == "mobile")
     {
          Do Stuff
     }
Adam
  • 2,632
  • 8
  • 34
  • 60
  • 1
    A better approach would be checking user-agent at server side and changing markup as needed. Check : http://stackoverflow.com/questions/1005153/auto-detect-mobile-browser-via-user-agent – Chandu Nov 13 '12 at 01:07
  • +1 Chandu's comment plus set a cookie and only run the detection script if the cookie is not set yet. – Troy Watt Nov 13 '12 at 01:40
  • or use responsive design and skip mobile version altogether. and I don't see why you need postback it looks like you have all the pieces figured out. Or you if you can detect and just set a mobile theme / master page. mixture of code behind and javascript is not necessary. – MikeSmithDev Nov 13 '12 at 01:44

1 Answers1

1

If you don't want to use responsive design, you can detect user agent like they mentioned in comments. Code behind would be:

   string theAgent = Request.UserAgent;
... run your check to see if mobile... change functionality, set cookie, etc.

You could also do this in the global.ascx and load a different MasterPage (a mobile master page) if you wanted.

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89