Thursday, July 23, 2015

Creating Custom Action Filters in ASP.NET MVC

I recently had a need to create a custom Action Filter in ASP.NET MVC to perform some pre-processing before I executed my Controller Action Methods.

I followed these MSDN articles to get started creating my Custom Action Filter:

https://msdn.microsoft.com/en-us/library/dd381609%28v=vs.100%29.aspx

https://msdn.microsoft.com/en-us/library/dd410056%28v=vs.100%29.aspx

However, there was not a great deal of insight on how to pass values and use values in my ActionFilter as well as how to create a custom ViewResult (such as by adding errors to the ModelState Errors collection).

Therefore, I played around with some code until I was finally able to get this code sample working:

namespace MvcFilters
{
    public class CustomFilterAttribute : ActionFilterAttribute
    {
        public string ModuleName { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool myValue = true;
            if (myValue)
            {
                base.OnActionExecuting(filterContext);
            }//if
            else
            {
                filterContext.Result = new CustomResult(this.ModuleName);
            }
            
        }
 
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
    }
 
 
   
}


namespace MvcFilters
{
    public class CustomResult : ViewResult
    {
        public CustomResult(string moduleName)
        {
            string strErrorMessage = string.Format("{0} cannot be used", moduleName);
            this.ViewData.ModelState.AddModelError("", strErrorMessage);
        }
 
        public override void ExecuteResult(ControllerContext context)
        {
            base.ExecuteResult(context);
        }
    }
}

Then, in order to use my ActionFilterAttribute in my ASP.NET MVC Controller, I simply decorate my ActionMethod in the following manner:



[HttpGet]
[CustomFilter(ModuleName ="Module1")]
public ActionResult Module1()
{
   return View();
}

 

That was all that was needed to get my Custom ASP.NET MVC ActionFilter to work and return my ModelState Error messages!!

1 comment:

  1. Hey, Nice information about ASP.NET MVC. Thanks to share. I have a little bit knowledge about asp.net mvc from Myasp.net. It is a good hosting site ,where I hosted my website.

    ReplyDelete