I’m not positive, but I think this is an MVC routing problem. I still don’t fully understand how routing works in MVC.
Lets say I have several action methods that I’ve applied a custom filter attribute to:
[MyAttribute]
public ActionResult Method1()
{
...
}
[MyAttribute]
public ActionResult Method2()
{
...
}
These methods normally don’t accept any parameters. Unfortunately the requirements have changed and now all of these methods might be receiving an optional parameter called “MyParameter”. If the parameter is passed in then a property in the ViewBag will be set.
In the actual project, there are ~70 of these methods. I was hoping to do it via the “MyAttribute” filter, because it already exists. So I would add something like this to the “MyAttribute” filter:
public class MyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
... // other existing code
// If a certain parameter was passed, I want to set a ViewBag property.
if( filterContext.ActionParamenters.ContainsKey("MyParameter") )
filterContext.Controller.ViewBag.MyProperty = filterContext.ActionParamenters["MyParameter"];
}
}
But unless the method’s definition has “MyParameter” in it as a parameter, it doesn’t see it in the ActionParameters collection. This is what makes me think it is a routing issue.
I would really prefer to not need to add the argument to all of the methods, but if there’s no other way to then I can. Any suggestions or ideas would be appreciated.
I found and went with this: