Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC route with array of homogeneous parameters

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: 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!

like image 919
Polina Avatar asked Oct 06 '10 16:10

Polina


1 Answers

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 ();
like image 186
eglasius Avatar answered Nov 21 '22 19:11

eglasius