sf.
sf.

Reputation: 25470

Querystring Route in MVC2

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?

Upvotes: 1

Views: 813

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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 }
);

Upvotes: 2

Related Questions