ASP.NET MVC - Current Action from controller code?

后端 未结 3 1316
感动是毒
感动是毒 2021-02-07 20:13

This is very similar to another recent question:

How can I return the current action in an ASP.NET MVC view?

However, I want to get the name of the current actio

3条回答
  •  借酒劲吻你
    2021-02-07 20:39

    Well if you are in the controller you know what action is being called. I am guessing that you have a class that is being used in the controller that needs to behave differently based on the action that is being called. If that is the case then I would pass a string representation of the action into the object that needs this information from within the action method. Some sample code from you would really clarify what you are needing to do. Here is some sample code that I am thinking:

    public ActionResult TestControllerAction()
    {
         var action = new TestControllerAction();
         var objectWithBehaviorBasedOnAction = new MyObjectWithBehaviorBasedOnAction();
         objectWithBehaviorBasedOnAction.DoSomething(action);    
    }
    
    public class MyObjectWithBehaviorBasedOnAction: IMyBehaviorBasedOnAction
    {
        public void DoSomething(IControllerAction action)
        {
          // generic stuff
        }
        public void DoSomething(TestControllerAction action)
        {
           // do behavior A
        }
        public void DoSomething(OtherControllerAction action)
        {
            // do behavior b
        }
    }
    
    public interface IMyBehaviorBasedOnAction
    {
       void DoSomething(IControllerAction action);
    }
    

提交回复
热议问题