Question

This is the scenario:

We want route like "{param1}{param2}" which param1 is string type and param2 is int type. As we know, two continuous arguments is not support by ASP.NET MVC routes. And I know, we can analysis route like "{param1}/{param2}", but that is not what I want.

So my question is that how to implement the scenario for two continuous arguments in MVC routes?

Was it helpful?

Solution

You need to write your custom MvcRouteHandler

public class MyRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var param = requestContext.RouteData.Values["param"].ToString();
        var sbString = new StringBuilder();
        var sbInt = new StringBuilder();

        foreach (var ch in param.ToCharArray())
        {
            if (char.IsDigit(ch))
                sbInt.Append(ch);
            else
                sbString.Append(ch);
        }

        requestContext.RouteData.Values["param1"] = sbString.ToString();
        requestContext.RouteData.Values["param2"] = sbInt.ToString();

        return base.GetHttpHandler(requestContext);
    }
}

Add in global.asax your route and specify the custom RouteHandler that it will use.

routes.MapRoute(
    "Default",
    "Test/{param}",
    new { controller = "Default", action = "Index"}
).RouteHandler = new MyRouteHandler();

Use param1 and param2 as action parameters.

public string Index(string param1, int param2)
{
    return param1 + "|" + param2;
}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top