3

In an asp.net MVC application, I need to produce some documens, HTML and PDF, which are not sent to the user's browser, but either sent by mail or entered in our document journalizing system. I produce these documents using Razor.

When a document is used only once, I just add a method to the relevant controller, and the view to that controller's view folder. This works. But I have a document that must be produced at two places in the application, implemented in separate controllers. I have made a new controller for this document with its own view folder.

My question is now: how do I call a method on this controller? Searching the web gives many answers, but all redirect the user to this document, which is not what I need.

  • You shouldn't _want_ to call a controller method yourself. Put the logic in a separate class, in its own method and call that. See also [.NET MVC Call method on different controller](http://stackoverflow.com/questions/1296680/net-mvc-call-method-on-different-controller). – CodeCaster Jul 21 '15 at 08:49

2 Answers2

3

You can just call it like you would any other method e.g.

public ActionResult DoSomething()
{
    // Some code
    var otherController = new OtherController(); // The other controller where the method is
    otherController.CreatePdf(); // Call the method

    // Continue with what ever else you need to do

    return View(); // This will then return the `DoSomething` View
}

But personally it doesn't seem like this logic belongs in a controller. You should possibly think about refactoring this logic out of a controller and into a more logical place. Possibly create your own document generation class and use that.

Jamie Rees
  • 7,973
  • 2
  • 45
  • 83
1

If I'm getting you right.You could create a base controller and add the method there. You can inherit the Base controller in any controller where you want to call the method. here's a link that might help show you the use of Base controllers. How to wire common code from a base controller in ASP.NET MVC.

Community
  • 1
  • 1
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38