CakePHP回调函数在ASP.Net MVC中等效

时间:2012-05-28 20:52:36

标签: asp.net asp.net-mvc asp.net-mvc-3 cakephp

我是ASP.Net MVC的新手,想知道是否有与CakePHP beforeFilter()afterFilter()beforeRender()等等的回调函数或方法等效。

我要做的是使用ViewBag设置一些全局变量,例如PageTitle,例如我有多个模块共享相同的标题和其他属性。

我以前也喜欢在CakePHP中使用一个名为AppController的父类,它可以实现那些使我能够运行函数并将变量发送到我的视图的回调函数。我在ASP.Net MVC中做了类似的事情,但它现在没用了,因为我无法启动我希望在Index()函数运行之前运行的函数。

AppController.cs

public class AppController : Controller
{
    public static string message = "Nice!";

    public void PageInfo()
    {
        ViewBag.Message = message;
    }
}

HomeController.cs

public class HomeController : AppController
{
    public ActionResult Index()
    {
        PageInfo();
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

我知道这听起来很傻,但作为一个ASP.Net初学者是一种可怕的感觉,所以对我来说很容易!

由于

2 个答案:

答案 0 :(得分:2)

您可以编写自定义操作过滤器:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // This will run before the action
        filterContext.Controller.ViewBag.Message = "some message";
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        // This will run after the action
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        // This will run before the result executes
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // This will run after the result executes
    }
}

然后用它装饰你的控制器(在这种情况下它将适用于这个控制器中的所有动作)或个别动作:

[MyActionFilter]
public class HomeController : AppController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

答案 1 :(得分:0)

您只需要创建自定义操作过滤器,实现抽象ActionFilterAttribute及其方法:

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted
相关问题