asp.net-mvc - 如何在 .NET 4 MVC 中从一个 Controller 调用另一个 Controller 的方法

标签 asp.net-mvc asp.net-mvc-4

在 asp.net MVC 应用程序中,我需要生成一些文档、HTML 和 PDF,它们不会发送到用户的浏览器,而是通过邮件发送或输入到我们的文档分类系统中。我使用 Razor 生成这些文档。

当一个文档只被使用一次时,我只是将一个方法添加到相关的 Controller 中,并将 View 添加到该 Controller 的 View 文件夹中。这行得通。但是我有一个文档必须在应用程序的两个地方生成,在单独的 Controller 中实现。我为这个文档创建了一个新的 Controller ,它有自己的 View 文件夹。

我现在的问题是:如何调用此 Controller 上的方法?搜索网络给出了很多答案,但都将用户重定向到该文档,这不是我需要的。

最佳答案

您可以像调用任何其他方法一样调用它,例如

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
}

但就我个人而言,这个逻辑似乎不属于 Controller 。您可能应该考虑将此逻辑从 Controller 重构到更合乎逻辑的位置。可能创建您自己的文档生成类并使用它。

关于asp.net-mvc - 如何在 .NET 4 MVC 中从一个 Controller 调用另一个 Controller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31534292/

相关文章:

asp.net - WindowsIdentity.RunImpersonated 导致 ASP.NET Core 3.1 上的 System.Net.Http.HttpRequestException

c# - 如何使用 DataAnnotation 属性在控制台应用程序中验证模型

asp.net - InProc session 超时不起作用

javascript - 第二次单击浏览器文件按钮时上传图像

javascript - TinyMCE 验证给出错误 : Cannot call method 'getContent' of undefined

c# - 如何异步更新 ASP.NET MVC 分部 View ?

c# - 如何使用 MVC4/Razor 下载文件

jqgrid - 无法让 jquery.jqgrid 4.4.1 在 ASP.NET MVC 中工作

c# - 无法访问已处置对象 MVC4 View

javascript - 如何将 json POST 数据作为对象传递给 Web API 方法?