Home > ASP.NET MVC > Custom Action filter in MVC 3

Custom Action filter in MVC 3


As we know that there are numbers of attribute based filter are provided by MVC framework , but in case that all does not meet our requirement we can create our own custom filter and resister it in our application.so before proceeding with this blog post i would recommend you to visit my blog post Filter in MVC to have basic understanding of what actually filter is and its scope in MVC .

So to create Custom Action filter

–Create a class that would either inherit from ActionFilterAttribute or implement IActionFilter, IResultFilter
–Then use this class as attribute on action method or Controller class.
–Or you can register it globally using Global.asax that basiccaly called Global Action filter that is new feature of MVC 3

let’s first create a class that would either inherit from ActionFilterAttribute

public class MVC3CustomActionAttribute : ActionFilterAttribute//(IActionFilter, IResultFilter)
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {

        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            ViewResult view = filterContext.Result as ViewResult;
            if (view != null)
            {
                view.ViewBag.Message = "Changed in OnResultExecuting" + view.ViewData["Message"].ToString();
            }
        }
    }

Then use this class as attribute on action method

[MVC3CustomAction]
public ActionResult Index()
{
   ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
   return View();
}

Or register it globally using Global.asax

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            RegisterGlobalFilters(GlobalFilters.Filters);

        }
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {

            filters.Add(new MVC3CustomActionAttribute());

        }
    }
}

Do not forget to like or comment 🙂

Advertisements
Categories: ASP.NET MVC Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: