How to set values to ViewBag in ActionFilterAttrib

2019-01-25 02:30发布

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 ?

3条回答
不美不萌又怎样
2楼-- · 2019-01-25 02:50

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);

}
查看更多
Melony?
3楼-- · 2019-01-25 03:02

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();
}
查看更多
\"骚年 ilove
4楼-- · 2019-01-25 03:02

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";
    }
}
查看更多
登录 后发表回答