Is there a way to return the same data for every ASP.Net MVC action in a particular controller?

I have a controller with several actions that return a data set, one of them. Instead of adding data to the ViewBag in each separate action, is there any template or attribute or something that I can call or set to add the same data to the viewdata or viewbag for each action or some other better a way to execute the same data in all views without calling a method in every action?

+8
asp.net-mvc
source share
2 answers

What you are looking for is an ActionFilter , and then override OnActionExecuting . Here is one of my ActionFilters that adds the currently logged in user to the ViewBag:

 public class AppendUserActionFilterAttribute : ActionFilterAttribute { ... public override void OnActionExecuting(ActionExecutingContext filterContext) { User currentUser = _sessionManager.CurrentUser; dynamic viewBag = filterContext.Controller.ViewBag; viewBag.CurrentUser = currentUser; } ... } 

Then you need to apply the attribute wherever you want it to happen. If you add it to an action, this action will receive the added entry in the ViewBag. If you add it to the controller, all its actions will receive it. If you add it to the base controller and turn on all its controllers, then all your actions in the entire application will receive it

  [AppendUserActionFilter] public class MyController : Controller { public ActionResult Foo() { .... } } 
+14
source share

One workable solution that can be assigned through the constructor of your controller

 public class HomeController : Controller { public HomeController() { ViewData["Common"] = "Some Data"; } }
public class HomeController : Controller { public HomeController() { ViewData["Common"] = "Some Data"; } } 

It will be available for all actions in the HomeController.

+3
source share

All Articles