3

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
  • what does your URL look like? Commented Mar 6, 2010 at 6:04
  • In this case, my URL is just accessing the Index action method (home page). So it would just be localhost Commented Mar 6, 2010 at 6:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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: Did you try this solution:)? It works for parameters set in filter.
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: 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?
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?
|
0

I'm hoping this will work:

var myParam = ValueProvider.GetValue("MyParam").RawValue as string;

Since ValueProvider is what modelbinders use to get the values I would think it should be able to get the value set in your filter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.