如何在ActionFilterAttribute ASP MVC 5中为ViewBag设置值?

时间:2014-06-25 12:16:33

标签: asp.net-mvc asp.net-mvc-5

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

4 个答案:

答案 0 :(得分:62)

你可以这样做

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

答案 1 :(得分:11)

试试这个

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

答案 2 :(得分:1)

从其他控制器操作传输数据

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

}

答案 3 :(得分:0)

对于ASP.NET Core,您可以执行以下操作

public class SomeFilterAttribute : IActionFilter
{
     public void OnActionExecuting(ActionExecutingContext context)
     {
         Controller controller = context.Controller as Controller;

         controller.ViewBag.CustomValue = customVal;
         controller.ViewData["CustomValue "] = customVal;
         controller.TempData["CustomValue "] = customVal;
     }
}

然后从控制器

    [TypeFilter(typeof(ValidateAppFeatureEnabled))]
    public IActionResult Index()
    {
        var foo = ViewBag.CustomValue;
        var bar = (type)ViewData["CustomValue"];
        var buzz = (type)TempData["CustomValue"];

        // Whatever else you need to do

        return View();
    }