In this post we are going to see how to create a custom action filter in ASP.NET MVC.  I am still using MVC 1 but I’m sure this’ll work just fine with MVC 2. I’ll update the post if it works differently on MVC 2.

See this link for an overview of action filters.

Say you have this problem like I did in one of my recent projects.
I needed to show a company logo on all pages but the home page. I know there are a million ways of doing this but I chose to use a custom action filter.

Here’s how I did.

Step 1.
I created a folder called Helpers and added the following class.  The only thing you need to do is inherit from ActionFilterAttribute class. For this particular case I am making the filter work with non AJAX, GET requests only. Notice that I am only adding some text ViewData which will be passed by the action method where we will apply the filter.

[sourcecode language=”csharp”]
public class DataForMasterPageAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//work fot GET requests only
if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
return;

//DO NOT work with AJAX requests
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
return;

filterContext.Controller.ViewData["message"] = "NoLogo";
}

}
[/sourcecode]

Step 2.
I applied the filter on my action method in the controller, in this case its the index action method which serves my homepage ( where the logo is not needed)

[sourcecode language=”csharp”]
[DataForMasterPage]
public ActionResult Index(int? page)
{
//implementation
return View();
}
[/sourcecode]

Step 3.

I added a simple conditional check on the master page thats checks if the page has the viewdata we passed with the filter. If it doesn’t exist we show the logo. If it exists we know its the home page so no logo is shown.

Simple as that.

[sourcecode language=”csharp”]
<% if((string)ViewData["message"] == null){ %>
<img src="../../Content/images/logo.jpg" alt="logo" height="77" width="263" />
<% } %>
[/sourcecode]
And that’s it.
This is just a very simple way to use custom filters. You can do much more powerful stuff with them.
Till next time, yours truly.

Custom Action Filters in ASP.NET MVC
Tagged on:         

2 thoughts on “Custom Action Filters in ASP.NET MVC

Leave a Reply

Your email address will not be published. Required fields are marked *