我在ASP.NET MVC 4项目中使用mvcsitemapprovider,我想知道是否可以根据查看页面的设备是否是移动设备来控制是否显示导航链接(基本上我只想在移动设备上支持我的应用程序的某些区域。)
这可能吗?我已经对此进行了搜索,但如果重复现有问题,则没有发现任何遗憾。
答案 0 :(得分:1)
public class MobileVisibilityProvider : SiteMapNodeVisibilityProviderBase
{
public bool IsVisible(ISiteMapNode node, IDictionary<string, object> sourceMetadata)
{
// Optional - You can use custom attributes to set different options
// specific to this visibility provider.
string visibility = node.Attributes["visibility"];
if (string.IsNullOrEmpty(visibility))
{
return true;
}
visibility = visibility.Trim();
// See the following answer for some advice about how
// to make this work with the latest browsers
// http://stackoverflow.com/questions/5233090/how-do-i-detect-a-mobile-browser-in-a-net-mvc3-application
if (HttpContext.Current.Request.Browser.IsMobileDevice && visibility.ToUpper() == "FALSE")
{
return false;
}
// If the logic is indeterminate in this visibility provider for
// any reason, default to true
return true;
}
}
然后,您可以通过调用此可见性提供程序为您的节点上的移动设备设置可见性。
<强> XML 强>
<mvcSiteMapNode title="Some Node" controller="Home" action="Contact" visibilityProvider="MyNamespace.MobileVisibilityProvider, MyAssembly" visibility="false" />
.NET属性
[MvcSiteMapNode(Title = "Some Node", VisibilityProvider = "MyNamespace.MobileVisibilityProvider, MyAssembly", CustomAttributes = @"{ ""visibility"": ""false"" }")
请注意,您还可以使用Default Visibility Provider设置在SiteMap范围内设置可见性提供程序,因此您无需在每个适用的节点上设置visibilityProvider。但是只能有1个默认可见性提供程序(使用内部DI容器),并且将其设置为FilteredSiteMapNodeVisibilityProvider通常是一个更灵活的选项。