asp.net-mvc 如何在 ActionFilterAttribute ASP MVC 5 中为 ViewBag 设置值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24408441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:44:51  来源:igfitidea点击:

How to set values to ViewBag in ActionFilterAttribute ASP MVC 5?

asp.net-mvcasp.net-mvc-5

提问by Arbejdsgl?de

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 ?

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

回答by Ilya

You can do like this

你可以这样做

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

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

Using:

使用:

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

回答by Anto Subash

try this

尝试这个

public class CustomFilterAttribute : ActionFilterAttribute
{
    public override void
    OnActionExecuting(ActionExecutingContext filterContext)
    {
        //  get the view bag

        var viewBag = filterContext.Controller.ViewBag;

        // set the viewbag values
        viewBag.CustomValue = "CustomValue";
    }
}

回答by Arun Prasad E S

To transfer data from a different controller action

从不同的控制器操作传输数据

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    EmployeeTrackingSystemAndMISEntities db = new EmployeeTrackingSystemAndMISEntities();

    var UserCookie = filterContext.HttpContext.Request.Cookies["UserUniqueID"];


    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
    redirectTargetDictionary.Add("action", "UserLogIn");
    redirectTargetDictionary.Add("controller", "Login");

    var TempData = filterContext.Controller.TempData;
    TempData["Status"] = "Please log in as Admin";

    filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);

}