tags:

views:

57

answers:

1

This must be simple, but I can't seem to figure it out. I am setting an action parameter inside an action filter as follows:

public class MyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting (ActionExecutingContext filterContext)
    {
        filterContext.ActionParameters["MyParam"] = "MyValue";
    }
}

I am applying the filter to an entire controller as follows:

 [MyFilter]
 public class HomeController : Controller
 {
      public ActionResult Index()
      {
           // How do I access MyParam here?
           return View();
      }
 }

}

How do I access MyParam inside an action method?

+2  A: 

Maybe you could use:

[MyFilter]
public ActionResult Index(string MyParam)
{
       //Do something with MyParam           
       return View();
}

You can decorate whole controller with [MyFilter] or only one action.

LukLed
MyParam is not coming from the URL, it is being set inside the action filter using the ActionParameters property. My code is more complicated, I gave a simple example for clarity.
Ralph Stevens
@Ralph Stevens: Did you try this solution:)? It works for parameters set in filter.
LukLed
I agree that it may work, but this may not be a very elegant solution. The filter will be applied to the entire controller. Some of the action methods will use it, others may not. There must be another way of accessing the action parameters (as needed) from inside the action method.
Ralph Stevens
@Ralph Stevens: So some action methods will have this parameter, others won't. You don't have to define this parameter in every action method. I can say that setting parameter when it is not needed is not elegant:) Why do you say that accessing parameter in strongly typed manner is not elegant?
LukLed
I see. So I would only declare it in some of the methods. Would passing this parameter to the action method affect the rest of the URL parameters passed into the same action method?
Ralph Stevens
@Ralph Stevens: No, it wouldn't. You can change these parameters by messing with `filterContext.ActionParameters`.
LukLed
Thanks for your help.
Ralph Stevens