如何在 ActionFilterAttribute ASP MVC 5 中为 ViewBag 设置值? [英] How to set values to ViewBag in ActionFilterAttribute ASP MVC 5?

查看:10
本文介绍了如何在 ActionFilterAttribute ASP MVC 5 中为 ViewBag 设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想为应用程序中的每个控制器创建自定义 ActionFilterAttribute,该属性应设置一些 ViewBag 值.ActionFilterAttribute 是否适合它以及如何访问 ActionFilterAttribute 中的视图包?

Hello I would like to create my custom ActionFilterAttribute for each controller in my application, this attribute should set some ViewBag values. Is ActionFilterAttribute would be fine for it and how to get access to viewbag in ActionFilterAttribute ?

推荐答案

你可以这样做

public class SomeMsgAttribute : FilterAttribute, IResultFilter
{
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
        }

        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.Msg= "Hello";
        }
}

使用:

[SomeMsg]
public ActionResult Index()
{
    return View();
}

这篇关于如何在 ActionFilterAttribute ASP MVC 5 中为 ViewBag 设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆