ASP .NET MVC 3 + Calling an HttpPost Action Method From a Different Controller

1.5k views Asked by At

I am currently developping a full-web application under VS2010 and I am using the ASP .NET MVC 3 framework.

Here is a simplified overview of my application :

  • I have implemented a controller Ctrl1.
    • Ctrl1 contains a HttpGet action method ActMeth1.
      • The Ctrl1Views folder contains a view View1.
  • I have implemented a controller Ctrl2.
    • Ctrl2 contains a HttpPost action method ActMeth2.
      • ActMeth2 returns a view View2 included in the Ctrl2Views folder.
  • Ctrl1 and Ctrl2 are in the same namespace.

I want ActMeth1 to call ActMeth2 to perform some logic and then to return View2.

Here is the source code of ActMeth1 :

public ActionResult ActMeth1()
{
    Ctrl2 myCtrl2 = new Ctrl2();
    return myCtrl2.ActMeth2();
}

Unfortunately ActMeth1 returns View1.
Does someone can give me an explanation to this fact ?
Thanks in advance for your future help

2

There are 2 answers

1
Ian Routledge On

You could do:

public ActionResult ActMeth1()
{
    Ctrl2 myCtrl2 = new Ctrl2();
    myCtrl2.ActMeth2();
    return View("~/Views/Ctrl2Views/View2.cshtml");
}

I'm not sure you should be instantiating controller 2 from inside controller 1 though...

0
chandmk On

Instantiating a controller's action method in another controller's action method is inviting trouble in the long run.

You can use tempdata, or pass the data via route dictionary of RedirectToAction.

I think you better reorganize your logic

As you are trying to do this logic in server side anyway,

a. Create a service that does the work for both the controllers b. make the view shared between both the controller actions or create a partial view for the common html c. Call the appropriate service method and render the shared view