How to set values to ViewBag in ActionFilterAttrib

2019-01-25 02:06发布

问题:

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 ?

回答1:

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


回答2:

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";
    }
}


回答3:

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

}