Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In my application I have a string parameter called "shop" that is required in all controllers, but it needs to be transformed using code like this:

        shop = shop.Replace("-", " ").ToLower();

How can I do this globally for all controllers without repeating this line in over and over? Thanks, Leo

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Write a custom action filter, override OnActionExecuting() and apply the filter to all your controllers. (Or simply overriding OnActionExecuting() in your base controller, if you have a base controller at all.) The action method would look something like this:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var parameters = filterContext.ActionParameters;
    object shop;
    if (parameters.TryGetValue("shop", out shop))
    {
        parameters["shop"] = ((string)shop).Replace("-", " ").ToLower();
    }
}
share|improve this answer
    
Thanks for your quick reply Buu, it worked great! This solution removed 31 redundant lines of code in my app! Leo –  user308166 Apr 4 '10 at 3:38
    
@Leonardo: my pleasure, I'm glad it worked for you! –  Buu Nguyen Apr 4 '10 at 5:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.