IT

Mvc의 컨트롤러에서 다른 컨트롤러를 호출하는 방법

lottoking 2020. 6. 24. 07:23
반응형

Mvc의 컨트롤러에서 다른 컨트롤러를 호출하는 방법


컨트롤러 A에서 컨트롤러 B 조치 FileUploadMsgView를 호출하고 이에 대한 매개 변수를 전달해야합니다.

 Code---its not going to the controller B's FileUploadMsgView().
    In ControllerA
  private void Test()
    {

        try
        {//some codes here
            ViewBag.FileUploadMsg = "File uploaded successfully.";
            ViewBag.FileUploadFlag = "2";

            RedirectToAction("B", "FileUploadMsgView", new { FileUploadMsg = "File   uploaded successfully" });
        }

     In ControllerB receiving part
  public ActionResult FileUploadMsgView(string FileUploadMsg)
    {
         return View();
    }

컨트롤러는 클래스 일뿐입니다. 새로운 클래스이며 다른 클래스 멤버와 마찬가지로 액션 메서드를 호출하십시오.

var result = new ControllerB().FileUploadMsgView("some string");


@mxmissile이 수락 된 답변에 대한 의견에서 말했듯이 컨트롤러는 IoC에 대해 설정된 종속성이 누락되어 있고을 갖지 않기 때문에 컨트롤러를 새로 시작해서는 안됩니다 HttpContext.

대신 다음과 같이 컨트롤러 인스턴스를 가져와야합니다.

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

샘플은 유사 코드처럼 보입니다. 다음 의 결과 반환 해야합니다 RedirectToAction.

return RedirectToAction("B", 
                        "FileUploadMsgView",
                        new { FileUploadMsg = "File uploaded successfully" });

@DLeh는 오히려 사용이라고 말합니다.

var controller = DependencyResolver.Current.GetService<ControllerB>();

그러나 컨트롤러에 컨트롤러를 제공하는 것은 특히 User개체, Server개체 또는 HttpContext'자식'컨트롤러 내부 에 액세스해야 할 때 중요 합니다 .

코드 줄을 추가했습니다.

controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);

그렇지 않으면 System.Web을 사용하여 현재 컨텍스트에 액세스 Server하거나 초기 객체에 액세스 할 수 있습니다

NB : 프레임 워크 버전 4.6 (Mvc5)을 타겟팅하고 있습니다.


리졸버가 자동으로 그렇게하십시오.

내부 A 컨트롤러 :

public class AController : ApiController
{
    private readonly BController _bController;

    public AController(
    BController bController)
    {
        _bController = bController;
    }

    public httpMethod{
    var result =  _bController.OtherMethodBController(parameters);
    ....
    }

}

누구나 .net 코어 에서이 작업을 수행하는 방법을 찾고 있다면 시작시 컨트롤러를 추가하여 달성했습니다.

services.AddTransient<MyControllerIwantToInject>();

그런 다음 다른 컨트롤러에 주입

public class controllerBeingInjectedInto : ControllerBase
{
    private readonly MyControllerIwantToInject _myControllerIwantToInject

     public controllerBeingInjectedInto(MyControllerIwantToInject myControllerIwantToInject)
{
       _myControllerIwantToInject = myControllerIwantToInject;
      }

그럼 그냥 이렇게 불러 _myControllerIwantToInject.MyMethodINeed();


Dleh의 답변 은 정확하며 IoC에 대한 종속성을 설정하지 않고 다른 컨트롤러의 인스턴스를 얻는 방법을 설명합니다

However, we now need to call the method from this other controller.
Full answer would be :

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

//Call your method
ActionInvoker.InvokeAction(controller.ControllerContext, "MethodNameFromControllerB_ToCall");

This is exactly what I was looking for after finding that RedirectToAction() would not pass complex class objects.

As an example, I want to call the IndexComparison method in the LifeCycleEffectsResults controller and pass it a complex class object named model.

Here is the code that failed:

return RedirectToAction("IndexComparison", "LifeCycleEffectsResults", model);

Worth noting is that Strings, integers, etc were surviving the trip to this controller method, but generic list objects were suffering from what was reminiscent of C memory leaks.

As recommended above, here's the code I replaced it with:

var controller = DependencyResolver.Current.GetService<LifeCycleEffectsResultsController>();

var result = controller.IndexComparison(model);
return result;

All is working as intended now. Thank you for leading the way.


if the problem is to call. you can call it using this method.

yourController obj= new yourController();

obj.yourAction();

참고URL : https://stackoverflow.com/questions/16870413/how-to-call-another-controller-action-from-a-controller-in-mvc

반응형