Handling MVC2 variables with hyphens in their name

Posted by Jaxidian on Stack Overflow See other posts from Stack Overflow or by Jaxidian
Published on 2010-05-06T15:14:19Z Indexed on 2010/05/06 15:18 UTC
Read the original article Hit count: 306

I'm working with some third-party software that creates querystring parameters with hyphens in their names. I was taking a look at this SO question and it seems like their solution is very close to what I need but I'm too ignorant to the underlying MVC stuff to figure out how to adapt this to do what I need. Ideally, I'd like to simply replace hyphens with underscores and that would be a good enough solution. If there's a better one, then I'm interested in hearing it.

An example of a URL I want to handle is this:

http://localhost/app/Person/List?First-Name=Bob

with this Controller:

public ActionResult List(string First_Name)
{
    {...}
}

To repeat, I cannot change the querystring being generated so I need to support it with my controller somehow. But how?

For reference, below is the custom RouteHandler that is being used to handle underscores in controller names and action names from the SO question I referenced above that we might be able to modify to accomplish what I want:

public class HyphenatedRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
    {
        requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
        requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
        return base.GetHttpHandler(requestContext);
    }
}

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about asp.net-mvc-routing