Monday, April 9, 2012

Inside the MvcSiteMapProvider - Part 3: The ISiteMapVisibilityProvider

This part is all about the ISiteMapVisibilityProvider in the . The usage is well described on the wiki page, and is very easy to use.
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.

4 comments:

  1. Thanks for this article!

    It 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.

    ReplyDelete
    Replies
    1. Something fell out... trying again:
      both occurrences end with < / s t r i n g >

      Delete
  2. Thank you, it has been corrected

    ReplyDelete
  3. Can 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