Tag Archives: global filters

Pre-set common viewmodel properties before action result

So, I defined a master model that is shared by every view in my MVC site. This model defines a bunch of properties that are always used on every page, such as a page title, page description, the google tag manager code, etc.

I need this model to be filled before the action result, so that I can use those properties on the view.

In order to do this, I created a custom Action Filter Attribute that is used by every action:


    public class SetupMasterModelActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewResultBase result = filterContext.Result as ViewResultBase;
            if (result == null)
            {
                return;
            }

            MasterModel model = result.Model as MasterModel;
            if (model == null)
            {
                return;
            }

            SetupMasterModel(model);
            SetupViewBag(result, model);
        }

        private void SetupMasterModel(MasterModel model)
        {
            ...
        }

        private void SetupViewBag(ViewResultBase result, MasterModel model)
        {
            ...
        }
   }

Continue reading