我正在为 ASP.NET MVC 4 (RC) View 使用自定义 DisplayModes 以允许自定义 View 内容。
我对这个仅限移动应用程序的规则非常简单,并根据用户的内部配置文件/ session 配置定义:
DisplayModeProvider.Instance.Modes.Insert(0,
new DefaultDisplayMode("Tablet")
{
ContextCondition = (context =>
{
if (SessionManager.Current == null)
return false; // assume phone initially
if (SessionManager.Current.Session.ScreenWidth > 600)
return true;
return false;
})
});
DisplayModeProvider.Instance.Modes.Insert(0,
new DefaultDisplayMode("Phone")
{
ContextCondition = (context =>
{
if (SessionManager.Current == null ||
SessionManager.Current.Session.ScreenWidth <= 600)
return true; // assume phone initially
return false;
})
});
我现在可以创建使用 xxxx.Phone.cshtml 和 xxxx.Tablet.cshtml 的 View 。呈现正确的 View 。
但是, ViewContext.DisplayMode.DisplayModeId 总是返回空白。例如,在下面的页面中,我回显了显示模式和一个硬编码的 id 来告诉哪个 View 被渲染:
<div>@Model.Distance - @ViewContext.DisplayMode.DisplayModeId - Tablet</div>
我看到硬编码的平板电脑(或手机)值,但 DisplayModeId 始终为空白。
应该设置这个值吗?我认为这在以前的 MVC 4 beta 版本中有效,但我不是 100% 确定。
有任何想法吗?
最佳答案
如果我没记错的话,这可能会在 ContextCondition 设置为 null 时发生。
发生这种情况时,不会考虑所有其他 DisplayModeProvider。
您确定没有任何 ContextCondition 返回 null 吗?也许是因为委托(delegate)内部的异常?您是否尝试过返回固定值(出于测试目的?
关于asp.net-mvc - 为什么 ViewContext.DisplayMode.DisplayModeId 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11020852/