开发者

Can we call the Method of a controller from another controller in asp.net MVC?

Can we call the Method of a controller from another controll开发者_如何学Goer in asp.net MVC?


You could also simply redirect straight to the method like so:

public class ThisController 
{
    public ActionResult Index() 
    {
       return RedirectToAction("OtherMethod", "OtherController");
    }
}


Technically, yes. You can call a static method of a controller or initialize an instance of a controller to call its instance methods.

This, however, makes little sense. The methods of a controller are meant to be invoked by routing engine indirectly. If you feel the need to directly call an action method of another controller, it is a sign you need some redesign to do.


Well, there are number of ways to actually call an instance method on another controller or call a static method off that controller type:

public class ThisController {
  public ActionResult Index() {
    var other = new OtherController();
    other.OtherMethod();
    //OR
    OtherController.OtherStaticMethod();
  }
}

You could also redirect to to another controller, which makes more sense.

public class ThisController {
  public ActionResult Index() {
    return RedirectToRoute(new {controller = "Other", action = "OtherMethod"});
  }
}

Or you could just refactor the common code into its own class, which makes even more sense.

public class OtherClass {
  public void OtherMethod() {
    //functionality
  }
}

public class ThisController {
  public ActionResult Index() {
    var other = new OtherClass();
    other.OtherMethod();
  }
}


Try This.

var ctrl= new MyController();
ctrl.ControllerContext = ControllerContext;
//call action
return ctrl.Action();


As controllers are just classes: Yes, we can do it. We can do it by some of the following ways:

  1. By directly redirecting- return RedirectToAction("MethodName", "ControllerName");

  2. By creating object - ControllerName objController=new ControllerName(); objController.methodName(parameters)


Yes, you can call a method of another controller.

public ActionResult Index()
        {
            AccountController accountController = new AccountController {ControllerContext = ControllerContext};
            return accountController.Index();
        }

The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜