- Inside the MvcSiteMapProvider - Part 1
- Inside the MvcSiteMapProvider - Part 2: Dynamic node providers
- Inside the MvcSiteMapProvider – Part 3: The ISiteMapVisibilityProvider
- Inside the MvcSiteMapProvider - Part 4: The IAclModule
- Inside the MvcSiteMapProvider - Part 5: The ISiteMapNodeUrlResolver
Ever wanted to only show specific sitemap nodes to authenticated users or only unauthenticated? With a specific role? All this can be done in 5 minutes with the ISiteMapVisibilityProvider.
Authenticated visibility provider
The sample project included in the MvcSiteMapProvider source code implements visibility provider. And the source code looks like this:public class AuthenticatedVisibilityProvider : ISiteMapVisibilityProvider
{
public bool IsVisible(SiteMapNode node, HttpContext context, IDictionary<string, object> sourceMetaData)
{
return context.Request.IsAuthenticated;
}
}
Easy right? And you can probably figure out how to only show nodes to unauthenticated users.Role visibility provider
public class RoleVisibilityProvider : ISiteMapVisibilityProvider
{
public bool IsVisible(SiteMapNode node, HttpContext context, IDictionary<string,object> sourceMetaData)
{
return context.User.IsInRole("Admin");
}
}
Method arguments
The IsVisible method takes three parameters:- node : SiteMapNode
- You have probably guessed it. This is the node which visibility we are checking.
- context : HttpContext
- Again, a self describing parameter, the current HttpContext.
- sourceMetadata : IDictionary<string, object>
- This parameter is a little more difficult to figure out. Currently this dictionary only contains either zero on one element, but this could change in the future. The dictionary key is a friendly name for the type calling the method, only HtmlHelper are used at the moment, which means it is called from, you guessed it, an HtmlHelper. The value is the full name of the class calling the method.
So this parameter can be used to only show specific nodes, in specific contexts, like only the XmlSiteMapFile or only in breadcrumbs.
Thanks for this article!
ReplyDeleteIt seems that in Part 3 you pasted the "class AuthenticatedVisibilityProvider ..." twice. Also, both occurrences end with ; not sure why that is.
And could you also specify on the first page which MvcSiteMap version you used? I guess the current/latest; but one can never be sure, and in the future new versions might be created with possible different workings.
Something fell out... trying again:
Deleteboth occurrences end with < / s t r i n g >
Thank you, it has been corrected
ReplyDeleteCan someone tell me why the ISiteMapVisibilityProvider is not resolving. I believe I am having problem with the namespace. I am not sure if I need additional module to download. Please help.
ReplyDelete