Finding the "device mode" in MVC3 and Bootstrap: A comprehensive guide

I am currently working with MVC3 and Bootstrap Responsive. My goal is to determine through Razor (or javascript) which mode - desktop, tablet, or phone - is active in order to display the appropriate partial view based on the mode.

Here's an example of what I want to achieve:

@if( mode=='phone')
{
    @html.Partial("_partialPhone")
}
@if( mode=='desktop')
{
    @html.Partial("_partialDesktop")
}
...and so on

I prefer not to solely rely on ".visible-phone", "visible-tablet", and ".visible-desktop" css classes as they cause all partial views to be loaded in the DOM and rendered by the Razor engine, even though only one is displayed. This can negatively impact performance on phones and tablets.

If anyone has any suggestions or guidance on how to accomplish this task, it would be greatly appreciated.

Thank you.

Answer №1

Responsive design relies on media queries being processed by the browser.
But what if we turn that notion on its head?

Imagine a scenario where the server dictates the client's size based on data stored in a cookie.

Answer №2

Utilizing MVC4 should allow you to achieve this functionality (I cannot confirm if it is available in MVC3, but the example referenced below utilizes MVC4 as the basis for my response).

Implementing Switchable Mobile Views

It seems possible to create files named like [ActionName].Mobile.cshtml and have ASP.NET automatically use them when a request comes from a mobile device (customizable for tablets or other devices). A demonstration similar to your query can be found in Razor - showcasing different links based on the current display mode:

@if (Request.Browser.IsMobileDevice && Request.HttpMethod == "GET")
{
    <div class="view-switcher ui-bar-a">
        @if (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice)
        {
            @: Displaying mobile view
            @Html.ActionLink("Desktop view", "SwitchView", "ViewSwitcher", new { mobile = false, returnUrl = Request.Url.PathAndQuery }, new { rel = "external" })
        }
        else
        {
            @: Displaying desktop view
            @Html.ActionLink("Mobile view", "SwitchView", "ViewSwitcher", new { mobile = true, returnUrl = Request.Url.PathAndQuery }, new { rel = "external" })
        }
    </div>
}

If separate mobile and desktop views are in place, manual switching between partials may not be necessary.

Further information

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show information once options have been chosen from the dropdown menu in CodeIgniter

As a newcomer to this platform and to codeigniter and Ajax, I'm seeking assistance. I am looking to dynamically display data without reloading the page or using a submit button after selecting an option from a drop-down menu. Although I have successf ...

Tips for accessing a state from a different file in React

Recently, I embarked on a storybook project and decided to add a new custom component called ProductSize. Utilizing a hover state, I noticed that when I hover over the component, its className updates seamlessly. Excited by this progress, I took it a step ...

Modifying the appearance of Bootstrap button colors

I recently came across this code on the Bootstrap website. I am curious about how to change the text color from blue to black in this specific code snippet. Currently, the text is appearing as blue by default. For reference and a live example, you can vis ...

Troubleshooting problems with an Angular controller

I am currently working on developing a basic app that retrieves data from MongoDB. However, I encountered an error in the console: Uncaught TypeError: Cannot read property 'controller' of undefined at model.js:8 'use strict'; var mi ...

Ways to access specific elements of an array through filtering

I am currently working on a script that compares the coordinates from the browser with coordinates in an array. However, I am encountering an issue where the const 'matchgeosucursal' returns as 'undefined' even when I force the filter c ...

Trouble persists with Semantic-ui themes remaining unchanged even after running gulp build

I've been attempting to modify the semantic-ui theme in the theme.config file, but I'm not seeing any changes take effect. There are no errors showing up in gulp or anything. Even after deleting the semantic.min.css file and rebuilding it, chang ...

I tried utilizing the useState hook to store the value, but surprisingly, it failed to update

I am brand new to Reactjs and currently working on creating an address form that includes 3 select options for country, state, and city. I have implemented React hooks in my project, where the page fetches a list of countries upon initial load. Subsequentl ...

Methods for sending an indexed array object back to a getJSON request with jquery

When sending an Indexed Array to a PhP file on the server side using getJSON, it seems like using an associated array may be a better choice. However, the indexed array works fine and the data is successfully received on the server. I am able to process th ...

Explaining the Usage of Nav-pills in Bootstrap v4

I am looking to align my navigation bar across the width of the div. However, I am currently using Bootstrap v4 and the nav-justify class is not available yet. Below is the code snippet: <ul class="nav nav-pills"> <li class="nav-item"> ...

Utilizing the Context Object in a Slack API Bolt Project for seamless property transfer between methods

I'm currently working on a Slack app using the JavaScript Bolt framework. This app essentially listens for specific message keywords in channels and then forwards those messages to the users of the app. My main goal is to add a permalink to the forwa ...

If Gulp is running continuously, what output will I receive?

After reading a helpful post on StackOverflow about gulp tasks (viewable here), I came to the conclusion that it's not advisable to omit returning anything in a gulp task. For proper synchronization of asynchronous tasks, the caller should wait. Pres ...

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', &apos ...

Tips for saving an object as a child within a sub-collection reference in mongoose

I've been looking for a solution to my problem for days with no luck. When working with Firebase, we use db references and sub-references to store objects at specific paths and collections. I'm trying to achieve the same functionality in MongoDB ...

Calculate the total amount by multiplying the price and quantity values within nested arrays

I have a collection of objects with nested arrays structured like this [ { orderId: 123, orderStatus: 'Pending', date: 'June 13, 2020', products: [ {product: 'choco', price: 300, qty: 3}, {product: 'm ...

Utilizing FabricJS to create a canvas with synchronized scrolling to the window

In the process of developing an app, I am utilizing the Html2canvas library to capture a screenshot of the body. Once the screenshot is taken, it is displayed in a canvas component using the fabricJS framework. The canvas is set to have the same height and ...

How can one effectively capture and handle Ajax errors on a global scale in an ASP.NET MVC application?

Often I catch myself adding this (simplified) code in multiple javascript files: $(document).ajaxError(function (e, xhr, settings, exception) { alert('error in: ' + settings.url + ' \\n' + ...

Best practice in AngularJS: Conceal/unveil fresh DOM elements or compile

Just starting out with AngularJS and looking to adjust button behavior on the fly. Coming from a JQuery background, I'm used to using element.attr('ng-click', 'controller.function()'). However, it seems that AngularJS requires co ...

A step-by-step guide to dynamically binding values to all browser tabs using localStorage and AngularJS

I currently have two files named index.html and server.js in my project. Within my code, I am utilizing local storage to retain text data across tabs. Below is the snippet of my implementation. I have two main queries: 1. Will the data persist when I clo ...

Aligning text in a <td> cell within a PHP SQL presentation

I am facing an issue with a table in which data is displayed using SQL and PHP. The problem arises because the second column contains a picture (column named "thumbsrc"), causing the text in the first column (column named "photosrc") to not center itself a ...

How can we capture and execute a function on the server in Next.js in response to a user's request for the index page (/)?

Is it possible to use a middleware function or another method in Next.js to check if a user is trying to access the home page? My goal is to intervene when a user tries to reach the home page. Intercepting a URL request is quite straightforward with Next. ...