What are ActionFilters in MVC?

Answer

ActionFilters help you to perform logic while an MVC action is executing or after an MVC action has executed.

Figure: ActionFilters in MVC

Action filters are useful in the following scenarios:

  1. Implement post-processing logic before the action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.

You can create action filters by two ways:

  • Inline action filter.
  • Creating an ActionFilter attribute.

To create an inline action attribute we need to implement the IActionFilter interface. The IActionFilter interface has two methods: OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods.

public class Default1Controller : Controller , IActionFilter
{
    public ActionResult Index(Customer obj)
    {
        return View(obj);
    }
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        Trace.WriteLine("Action Executed");
    }
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        Trace.WriteLine("Action is executing");
    }
} 

The problem with the inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from ActionFilterAttribute and implement the IActionFilter interface as shown in the below code.

All asp.net-mvc Questions

Ask your interview questions on asp-net-mvc

Write Your comment or Questions if you want the answers on asp-net-mvc from asp-net-mvc Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---