Faisal
Faisal

Reputation: 200

ActionFilterAttribute mvc need to call One time

I have a scenario i need to check security for each menu item if user 'A' is allowed to access this menu or not and for that reason i created a class which is inherited with ActionFilterAttribute

public class SecurityFilter : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Log("OnActionExecuting", filterContext.RouteData);
    }
}

and using this class on my controller

[SecurityFilter]
public class XYZController : Controller
{ 
 public ActionResult Index() { 
   return View(); 
   } 
 }

Now the problem is in my View i have @Html.Action() calls e.g

  @Html.Action("COM")

which results in calling onActionExecuting Method again, i Just want it to call it one time when menu link is clicked and for that method only where menu is redirecting not the other Action method which is render inside view

Upvotes: 2

Views: 1428

Answers (1)

haim770
haim770

Reputation: 49095

When called using @Html.Action the IsChildAction property of the filterContext will be true. You can rely on it to determine whether you actually want to do something or not:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.IsChildAction)
        return;

    Log("OnActionExecuting", filterContext.RouteData);
}

See MSDN

Upvotes: 3

Related Questions