Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect a mobile browser in a .NET MVC3 application

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!

like image 908
Dave Avatar asked Mar 08 '11 13:03

Dave


People also ask

How can detect mobile device in asp net?

In ASP.NET, you can easily detect the mobile device request using Request. Browser. IsMobileDevice property and Request. UserAgent .

How can check website open in mobile or desktop in asp net?

You can use useragent in asp.net to verify the request are coming from mobile or desktop.

Does MVC use razor pages?

A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself. You do not need to add code separately.


2 Answers

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 --> } 
like image 67
tsiorn Avatar answered Oct 06 '22 02:10

tsiorn


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.

like image 43
Ryan Tofteland Avatar answered Oct 06 '22 00:10

Ryan Tofteland