Reputation: 10981
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
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
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
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):
Upvotes: 0
Reputation: 3199
check the value of: HttpContext.GetOverriddenBrowser().IsMobileDevice
Upvotes: 1