Click here to Skip to main content
Click here to Skip to main content

Device recognition in ASP.NET MVC 4

, 6 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Little and programmer-friendly library for device recognition for mvc 4 web apps.

Introduction

Nowadays mobiles and tablets are widely used for surfing on the web. So creating user-friendly applications for devices is a must. While playing around with my project I noticed that for tablets, desktop version (with slight modifications) looks better than mobile version. So I needed to identify if client was desktop, tablet, or mobile.

Background

I have not done much with MVC 4 so I googled for a solution and ended up with this article. I've decided to make it more comfortable for use in several projects.

Using the code

Default namespace I've chosen for this little helper library is System.Web.Helpers. I've used this namespace because I wanted to avoid config modification for view.

Library contains only three components:

  1. Class DeviceRecognitionHelper that has to be initialized in Application_Start, Global.asax and is intended for internal use mostly;
  2. Enumerable DeviceType which does not need much explanation.
  3. Extension methods for HttpRequestBase that allows directly calling these methods on the Request property.

Let's start with DeviceRecognitionHelper which needs to be initialized in Application_Start:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Other stuff here.
        DeviceRecognitionHelper.Initialize();
    }
}

There are five extension methods for HttpRequestBase: IsTablet(), IsMobile(), IsTv(), IsDesktop(), and GetDeviceType().

Sample usage in Razor view:

@Request.GetDeviceType()

<br />

@if (Request.IsMobile())
{
    <b>Request was from mobile</b>
}
else if (Request.IsTablet())
{
    <b>Request was from tablet</b>
}
else if (Request.IsTv())
{
    <b>Request was from tv</b>
}
else if (Request.IsDesktop())
{
    <b>Request was from desktop</b>
}     

Implementation of this library with sample MVC 4 app can be found in attached files.

Points of Interest

I found implementing this fun and, more importantly, useful in real-world projects. More user-friendly your application is more users it has. Smile | <img src=

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Leri Buiglishvili
Software Developer
Georgia Georgia
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 6 Jun 2013
Article Copyright 2013 by Leri Buiglishvili
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid