Tag Archives: actionfilter

Custom ActionFilterAttribute to pass data to the viewbag before the action executed

Currently projects the SEO setting has been manually hard code it to the view. But since the SEO setting will be frequently change, so my task is to move those hard code text to database, and for render it out to the page. I just created a ViewBag to pass those information to the view.

Asp.net mvc ActionFilterAttribute allow your to pre-process logic to the method before or after the method just executed.

How to do it, just create a class inherit from: ActionFilterAttribute, and inside this class you could see there are 4 members allow you to override it.

        public virtual void OnActionExecuted(ActionExecutedContext filterContext);      
        public virtual void OnActionExecuting(ActionExecutingContext filterContext);        
        public virtual void OnResultExecuted(ResultExecutedContext filterContext);        
        public virtual void OnResultExecuting(ResultExecutingContext filterContext);

For my task, I just overide the OnActionExecuting method.
here is my solution:
step1, create a class named: SeoSettingAttribute.cs

   public class SeoSettingAttribute : ActionFilterAttribute
        public override void OnActionExecuting(ActionExecutingContext filterContext)

            string action = filterContext.ActionDescriptor.ActionName;
            filterContext.Controller.ViewBag.SeoSettings = GetSeoSettings(action);

        private SeoSettingViewModel GetSeoSettings(string actionStr)
            SeoSettingViewModel seoModel = new SeoSettingViewModel();
            var AdminService = NinjectWebCommon.CurrentKernel.Get();
            seoModel = AdminService.GetCurrentSeoSetting(actionStr);

            return seoModel;


decorate it to your the method inside your controller that you like use it.

        public ActionResult Index(){....}