我正在开发移动网络应用程序。我需要让当前的显示模式在 Controller 中是移动的。
我的问题是:我有 2 个局部 View
/Views/Shared/ListItem.cshtml
/Views/Shared/ListItem.mobile.cshtml
当使用 PartialView("ListItem") 时,这是正确的。但我需要将部分 View 放在子文件夹中
/Views/Shared/Modules/Post/ListItem.cshtml
/Views/Shared/Modules/Post/ListItem.mobile.cshtml
当我使用 PartialView("~/Views/Shared/Modules/Post/ListItem.cshtml") 这适用于桌面。当显示模式为移动时,ListItem.mobile.cshtml
不显示。
我的选择是
if( CurrentDisplayMode==Mobile){
PartialView("~/Views/Shared/Modules/Post/ListItem.mobile.cshtml");
else
PartialView("~/Views/Shared/Modules/Post/ListItem.cshtml");
如何获取CurrentDisplayMode
?
如何解决这个问题?
最佳答案
我还需要访问当前显示模式,以便调整传递给 View 的 View 模型(移动 View 中的信息较少,因此可以从较小的 View 模型中显示)。
ControllerContext.DisplayMode
无法使用,因为它将在操作执行后设置。
所以你必须根据上下文(用户代理、cookie、屏幕尺寸等...)来确定显示模式
这是一个 nice trick I found on the ASP.NEt forums这将使您可以使用框架稍后将使用的相同逻辑来确定显示模式:
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.");
}
关于c# - 如何在mvc4中获取当前显示模式是移动的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10702825/