ebattulga
ebattulga

Reputation: 10981

How to get current displaymode is mobile in mvc4

I'm developing mobile web application. I need to get current displaymode is mobile in controller.

My problem is: I have 2 partialview

/Views/Shared/ListItem.cshtml
/Views/Shared/ListItem.mobile.cshtml

when use PartialView("ListItem") this is correctly works. But i need to put partialviews in sub folder

/Views/Shared/Modules/Post/ListItem.cshtml
/Views/Shared/Modules/Post/ListItem.mobile.cshtml

When i use PartialView("~/Views/Shared/Modules/Post/ListItem.cshtml") this works on desktop. when displaymode is mobile, ListItem.mobile.cshtml not displayed.

My choice is

if( CurrentDisplayMode==Mobile){
  PartialView("~/Views/Shared/Modules/Post/ListItem.mobile.cshtml");
else
  PartialView("~/Views/Shared/Modules/Post/ListItem.cshtml");

How to get CurrentDisplayMode ? How to solve this problem?

Upvotes: 10

Views: 3806

Answers (4)

Xavier Poinas
Xavier Poinas

Reputation: 19733

I also needed to access the current display mode so I could adjust the view model that was passed to the view (less information in the mobile view thus it can be displayed from a smaller view model).

ControllerContext.DisplayMode cannot be used because it will be set after the action has executed.

So you have to determine the display mode based on the context (user agent, cookie, screen size, etc...)

Here's a nice trick I found on the ASP.NEt forums that will let you determine the display mode using the same logic that will later be used by the framework:

public string GetDisplayModeId()
{
    foreach (var mode in DisplayModeProvider.Instance.Modes)
        if (mode.CanHandleContext(HttpContext))
            return mode.DisplayModeId;

    throw new Exception("No display mode could be found for the current context.");
}

Upvotes: 7

Tony
Tony

Reputation: 4609

The best option you have is checking the Request headers user agent field where you can listen for android iPhone etc. While that wont give you screen size and isnt going to work if you are not listening for nokia phones or something like that, this is a solution and allows you to limit what you support as most companies do.

Upvotes: 0

Dmitry
Dmitry

Reputation: 17350

I believe MS wants you to use this:

controller.ControllerContext.DisplayMode

It works but I found two major problem with it (as of the date of this post):

  1. Unit testing. DisplayMode property can not be set manually (throws NullReferenceException) and can not be mocked because it is not virtual.
  2. It does not work with MvcDonutCaching. DisplayMode simply returns NULL when requesting cached portion of the page.

Upvotes: 0

JTMon
JTMon

Reputation: 3199

check the value of: HttpContext.GetOverriddenBrowser().IsMobileDevice

Upvotes: 1

Related Questions