c# - 如何在mvc4中获取当前显示模式是移动的

标签 c# asp.net-mvc-4

我正在开发移动网络应用程序。我需要让当前的显示模式在 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/

相关文章:

asp.net-mvc - 如何将文件内容添加到Viewbag mvc4

jquery - Kendo Dropdownlist 与 json 对象的级联

c# - 使用 jQuery 将表单数据发布到 MVC4 Controller 操作方法时出现问题

c# - 以编程方式清除 Silverlight 应用程序存储?

C# 数据表错误

c# - XAML:为什么不能将 T 的子类添加到 T 的集合中?

asp.net-mvc - 如何在 MVC 中创建通用 View 模型?

c# - 为什么嵌套 if 语句可以工作,但 "&&"运算符却不能? (字母计数脚本)

c# - 使用 Winform 应用程序填写 PDF/表格

c# System.Diagnostics.Process 不执行任何操作或抛出错误