Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
ebattulga Avatar asked May 22 '12 13:05

ebattulga


1 Answers

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.");
}
like image 184
Xavier Poinas Avatar answered Oct 20 '22 11:10

Xavier Poinas