ASP.NET MVC Pass Object from Custom Action Filter to Action

If I create an object in the Custom Action Filter in ASP.NET MVC in

public override void OnActionExecuting(ActionExecutingContext filterContext) { DetachedCriteria criteria = DetachedCriteria.For<Person>(); criteria.Add("stuff"); // Now I need to access 'criteria' from the Action..... } 

is there any way to access the object from the action that is currently being executed.

+54
filter asp.net-mvc custom-action
Nov 27 '09 at 14:18
source share
4 answers

I would recommend putting it in the route data.

  protected override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RouteData.Values.Add("test", "TESTING"); base.OnActionExecuting(filterContext); } public ActionResult Index() { ViewData["Message"] = RouteData.Values["test"]; return View(); } 
+40
Nov 27 '09 at 16:07
source share
— -

the best approach is described by Phil Haack.

This is basically what you do:

 public class AddActionParameterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); // Create integer parameter. filterContext.ActionParameters["number"] = 123; // Create object parameter. filterContext.ActionParameters["person"] = new Person("John", "Smith"); } } 

The only result is that if you create object parameters, then your class (in this case Person) must have a default constructor, otherwise you will get an exception.

Here you can use the filter above:

 [AddActionParameter] public ActionResult Index(int number, Person person) { // Now you can use number and person variables. return View(); } 
+60
Nov 28 '12 at 18:23
source share

You can use the HttpContext :

 filterContext.HttpContext.Items["criteria"] = criteria; 

And you can read it in action:

 [YourActionFilter] public ActionResult SomeAction() { var criteria = HttpContext.Items["criteria"] as DetachedCriteria; } 
+30
Nov 27 '09 at 14:38
source share

Set an item in ViewData or in view mode if you pass it as a parameter to your action. Here I set the ViewModel property

 public override void OnActionExecuting(ActionExecutingContext filterContext) { ViewModelBase viewModel = null; foreach (object parameter in filterContext.ActionParameters.Values) { if (parameter is ViewModelBase) { viewModel = (ViewModelBase)parameter; break; } } if(viewModel !=null) { viewModel.SomeProperty = "SomeValue"; } } public ActionResult About(ViewModelBase model) { string someProperty= model.SomeProperty; } 

Here is an untyped version, I think you prefer:

  public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.ViewData.Add("TestValue", "test"); } [FilterWhichSetsValue] public ActionResult About() { string test = (string)ViewData["TestValue"]; return View(); } 
+3
Nov 27 '09 at 15:46
source share



All Articles