【问题标题】:Mvc3 C# - Is it possible to call an action from a different controller?Mvc3 C# - 是否可以从不同的控制器调用动作?
【发布时间】:2013-07-29 11:26:43
【问题描述】:

在我的项目中,我有两个不同的控制器。
这是主要的:

public class Main : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

这是另一个:

public class OtherOne : Controller
{
    public ActionResult RandomAction()
    {
        return ... //more code here
    }
}

我应该在 "OtherOne/RandomAction" 中返回什么以获得与 "Main/Index" 操作相同的结果?

【问题讨论】:

  • 你想达到什么目的?像“主/索引”这样的相同结果是什么意思。如果两个动作方法具有相同的逻辑,为什么你有两个动作?最简单的方法是使用 RedirectToAction 并将数据存储在可以在 Main/Index 中访问的 TempData 集合中。

标签: c# asp.net-mvc asp.net-mvc-3 http-redirect


【解决方案1】:

就这么简单:

public class OtherOneController : Controller
{
    public ActionResult RandomAction()
    {
        return RedirectToAction("Index", "Main");
    }
}

您的 Controller 类名必须是 MainController 和 OtherOneController。如果您想更改它,请查看此帖子: change controller name convention in ASP.NET MVC

这是你的主控制器:

public class MainController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多