ActionFilter to populate SiteMap

Aug 26, 2009 at 3:03 PM

I thought that an actionfilter would be perfect for setting the title in a sitemap instead of setting it directly in the controllers action.

I built this simple actionfilter to handle it for me

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class SiteMapTitleAttribute : ActionFilterAttribute
    {
        protected readonly string _propertyName;

        public SiteMapTitleAttribute()
        {
            _propertyName = "Name";
        }

        public SiteMapTitleAttribute(string propertyName)
        {
            _propertyName = propertyName;
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Result is ViewResult) {
                var result = (ViewResult)filterContext.Result;
                PropertyInfo propertyInfo = result.ViewData.Model.GetType().GetProperty(_propertyName);
                SiteMap.CurrentNode.Title = propertyInfo.GetValue(result.ViewData.Model, null).ToString();
            }
        }
    }


It uses reflection to find a property named "Name" if you haven't specified it.

In a real world example it would be coded like this

[SiteMapTitle("Headline")]
public ViewResult Show(int blogId) {
   var blog = _repository.Find(blogIdId);
   return blog;
}

The filter can of course be updated to take into consideration the length of parameter and so on..

Hope someone find this useful

Regards
Kenny Eliasson
Aug 27, 2009 at 8:02 AM

Thanks for this! It is really a welcome addition which is in the source code repository now. I've adapted it a little so it falls back to ViewData["headline"]  if no model is specified.