- Updating Device Data
- Web Apps
- SQL Server
- Reference Pages
- Useful Links
- Supported Versions
The easiest way to see how 51Degrees .NET API can be used within MVC is to open up the Visual Studio project from the GitHub repository and look at the MVC project inside the Examples folder. Below, we will go through the steps to recreate this project.
The first step is to install 51Degrees into your project. This example uses a new Visual Studio 2013 ASP.NET website with MVC NuGet package installed, but it should work for any version of Visual Studio, providing the project is using .NET 4 or above.
51Degrees can be found in Visual Studios NuGet package manager, or can be downloaded from GitHub. The package comes with an aspx test page which is not needed for this, so 'Mobile/Default.aspx' can be deleted.
All configuration is administered in 51Degrees.config. The redirect element in that file can be removed as redirection doesn't fit very well in MVC because controllers cannot be reused.
Code and Explanation
The first stage of using 51Degrees device detection in MVC is creating a model. This Device model can access the Match object in two ways:
Accessing the Match object directly
This is the most efficient method as it returns the requested property directly from the Match object
Reflecting the Match object properties
This uses reflection to set all the properties of the Device object, so with a large number of properties will be a less efficient method.
The BaseController overrides the initialize method and creates a Match object. It creates a new instance of the Device model using this match and makes it available in the ViewBag for use in cshtml pages. It also exposes the Match object directly via the ViewBag (the more efficient method).
Now any view from a controller extending BaseController can access these objects like
to print the IsMobile property for Device and Match objects respectively.
Using the Match object also makes it easy to access data set properties and match metrics like,
to print the data set published date and match method from the Match object.
Example MVC Mobile Output
You should now be able to navigate to this page and see information about your device displayed. If you're using a desktop browser then the information returned will be limited. To see a fuller set of data, either use the device emulation capabilities of the web browser to imitate a smartphone or tablet, or if possible use an actual mobile device.