views:

46

answers:

1

I trying to create routes for a resource with an array of homogeneous parameters.

URL would look like this: products/category/{categoryId1}/{categoryId2}/.../brand/{brandID1}/{brandID2}/...

And would like an action method would look like this: public ActionResult GetProducts(IList categoryID, ILIsts brandID) {...}

where category and brand are independent filters.

I found a solution for similiar task: http://stackoverflow.com/questions/3634582/asp-net-mvc-2-parameter-array

And wonder if there is no more beautiful solution that allow to use this prototype public ActionResult GetProducts(IList categoryID)

instead of public ActionResult myAction(string url)

for action method

-- to avoid splitting the string and casting?

And how could I suit this solution for my case?

Thank you everybody beforehand!

+1  A: 

Use a custom handler, like the one I posted in this answer.

Might need some adjustments, but something like this should work:

public class ProductsRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        IRouteHandler handler = new MvcRouteHandler();
        var vals = requestContext.RouteData.Values;
        vals["categoryID"] = vals["categories"].Split("/");
        vals["brandID"] = vals["brands"].Split("/");
        return handler.GetHttpHandler(requestContext);
    }
}

// in the route:
routes.MapRoute(
   "test",
   "products/category/{*categories}/brand/{*brands}",
   new { Controller = "product", Action = "getproducts"}
   ).RouteHandler = new ProductsRouteHandler ();
eglasius
Thank you for a nice solution! I just could not register such route: "products/category/{*categories}/brand/{*brands}". Runtime error occurs: A catch-all parameter can only appear as the last segment of the route URL
Polina
do "products/category/{*parameters}", and get the 2 pieces with .Split("/brand/") ... then its pretty much what's already in there :)
eglasius
... depending on your needs, you might want to also add a constraint over parameters so it only use the route if /brand/ is in there
eglasius