Search code examples
c#asp.net-mvc-5action-filter

Calling action filter automatically in MVC5


I'm trying to develop a plugin for nopcommerce and trying to catch model for a page (after submitted) in an action filter so that I can make some changes to model properties.

    public ActionResult Index()
    {
        Data dt = new Data();

        dt.id = 54;
        dt.name = "something";
        return View(dt);
    }

and this is the fitler:

public class ModelChangerAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Data dt = new Data();
            dt = (Data) filterContext.Controller.ViewData.Model;
            dt.id++;
            dt.name += " someotherthing";

            filterContext.HttpContext.Items["dt"] = dt;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //throw new NotImplementedException();
        }
    }

But for action filter to run I need to specify it before method in controller. And I'm not down with that.

don't want to do this:

        [ModelChangerAttribute]
        public ActionResult Index()
        {
            ...

So is it possible to call filter automatically each time a controller method is run?

Please provide an example HERE.


Solution

  • in App_Start/FilterConfig.cs:

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ModelChangerAttribute());
        }
    }
    

    Additional info: you should call this in global.asax in Application_Start():

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);