47

I'm developing a .NET MVC3 application.

Is there a good way to detect if the user is using a mobile browser in the view (using RAZOR). I'm wanting to differ the display logic if it's a mobile browser.

Thanks!

Dave
  • 5,998
  • 4
  • 29
  • 36
  • 4
    You may want to consider doing this at the controller level, and varying the actual view returned. – John Gietzen Mar 08 '11 at 13:29
  • 1
    Good point. I guess it depends on how extensive the changes. If it's just including a different css file, that should be done in the view. If it's a completely different view, it would be good to keep those completely separated. Thanks for the input. – Dave Mar 08 '11 at 13:36

3 Answers3

75

MVC3 exposes an IsMobileDevice flag in the Request.Browser object.

So in your razor code, you can query this variable and render accordingly.

For example, in your view (razor):

@if (Request.Browser.IsMobileDevice) {
  <!-- HTML here for mobile device -->
} else {
  <!-- HTML for desktop device -->
}
Konrad Gadzina
  • 3,277
  • 1
  • 15
  • 27
tsiorn
  • 2,156
  • 1
  • 20
  • 25
  • 14
    sure it does. im using it in production project. there are some limitations now as the mobile list is no longer kept up to date. You can use a 51degrees.mobi (see below post) for updated list. You still can then use this technique to detect a mobile browser. – tsiorn Jun 20 '11 at 13:18
  • 2
    @WhatsInAName is an ipad a mobile device? – wal Apr 05 '15 at 02:42
21

The built in browser detection capabilities are no longer being kept up to date. Take a look at Scott Hanselman's blog - refer to the "More to Come" section at the bottom for details.

From that article:

Since that post, the Live.com team in Ireland that released and supported the original Mobile Device Browser File (MDBF) has stopped producing it. The best source for mobile browser device data is WURFL (that was one of the places that MDBF pulled from.)

I suggest taking a look at 51Degrees.mobi for more accurate detection. Also see the Steve Sanderson blog that Hanselman references for how to implement this in MVC3.

jpaugh
  • 5,719
  • 4
  • 33
  • 83
Ryan Tofteland
  • 913
  • 6
  • 11
0

I use this Method (Works fine for Me)

if (eDurar.MobileDetect.DeviceType.Any(m => Request.UserAgent.Contains(m)))
{
    Layout = "~/Views/Shared/_mobileLayout.cshtml";
    @Html.Partial("mobileIndex");

}
else
{
    Layout = "~/Views/Shared/_Layout.cshtml";
    @Html.Partial("desktopIndex");
}

I suggest you to use responsive bootstrap something, avoiding mobile specific page is better

Arun Prasad E S
  • 7,342
  • 6
  • 61
  • 75