views:

19

answers:

1

I'm trying to create a route to a specific controller/action which needs to accept optional querystring parameters.

the urls i'd like to accept are:

/Products/ProductsListJson
/Products/ProductsListJson?productTypeId=1
/Products/ProductsListJson?productTypeId=1&brandId=2
/Products/ProductsListJson?productTypeId=1&brandId=2&year=2010

I have an action like this:

public JsonResult ProductsListJson(int productTypeId, int brandId, int year)

And a route like this:

routes.MapRoute(
    null, "Products/ProductsListJson",
    new { controller = "Products", action = "ProductsListJson", productTypeId = 0, brandId = 0, year = 0 }
);

I assumed that the action "ProductsListJson" would simply see the querystring urls and map them to the appropriate arguments however this is not happening.

Anyone know how this could be achived?

+2  A: 

You don't need to specify their values in the route if those parameters are passed in the query string:

routes.MapRoute(
    null, "Products/ProductsListJson",
    new { controller = "Products", action = "ProductsListJson" }
);

and your action:

public ActionResult ProductsListJson(int? productTypeId, int? brandId, int? year)
{
    ...
}

but you probably don't need a specific route for this as the default route will handle it just fine:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Darin Dimitrov
Thanks. I'd like them to default to 0 automatically. Is that possible? Or do i need to evaluate in the action?
sf
Well then simply use the [null coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx). Whenever you need to use them: `productTypeId ?? 0`
Darin Dimitrov
all good.. was hoping the route could handle that.. thanks for your help :)
sf