Sunday, 18 February 2018

What is ActionInvoker and how to create own custom action

First create a class and inherit it with ControllerActionInvoker class. By inheriting with ControllerActionInvoker class we will be able to control the default behavior of InvokeAction method by overriding it.
In this we have checked the name of the action and if it is "Left" then we are setting the ViewResult.View property to the "Right" view. This means if user request /ActionInvoker/Left url, the user sees the same url in the address bar but instead of seing "Left" view page he sees "Right" view page. If the actionName is different than "Left" then user gets the default behavior.
public class CustomDefaultActionInvoker : ControllerActionInvoker
{
        public override bool InvokeAction(ControllerContext controllerContext, string actionName)
        {
            if (actionName.Equals("Left"))
            {
                ViewResult result = new ViewResult();
                result.View = result.ViewEngineCollection.FindView(controllerContext, "Right", null).View;
                InvokeActionResult(controllerContext, result);
                return true;
            }
            else
            {
                return base.InvokeAction(controllerContext, actionName);
            }
        }
}
Once we have created this class and built the ASP.NET MVC proejct without error, we need to set the instance of this class to the ActionInvoker inside the Controller's constructor.
See the code snippet below and notice the constructor of this controller where we have set this.ActionInvoker property to the instance of the CustomDefaultActionInvoker class defined above.
 public class ActionInvokerController : Controller
    {

        public ActionInvokerController()
        {
            this.ActionInvoker = new CustomDefaultActionInvoker();
        }

        public ActionResult Left()
        {
            return View();
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Right()
        {
            return View();
        }
   }
Now if we make following request
  • /ActionInovker/Left - we see the address bar as /ActionInovker/Left but the actual output of this request would show the "Right" view.
  • /ActionInvoker/Index - we see the default view as in the CustomDefaultActionInvoker class we have not checked for actionName = "Index" and same is the case of other action methods.

No comments:

Post a Comment