annantDev
annantDev

Reputation: 367

writing route in mvc4 to eliminate query string

I have a situation where I am redirecting to an action that accepts 3 parameters. This I am doing like -

RedirectToAction("ProductSpecific", routeValues: new { partId = m.partId, categoryId= m.categoryId, categoryName = m.categoryName});

However, when the page loads, it contains all these parameters as query string.

Parts/ProductSpecific?partId=38&categoryId=1&categoryName=Monitor

I tried writing a route, but that didn't work. Can someone please guide on how to write a route in this scenario?

Thanks

Upvotes: 0

Views: 652

Answers (1)

gdp
gdp

Reputation: 8252

The second argument of RedirectToAction is routeValues, so these will be appended to the querystring. Creating an extra route will still require you passing the values in the querystring, but like this: parts/productspecific/{partId}/{categoryId}/{categoryname} which i dont think you want.

If you dont want the values in the querystring, have a look at the TempData object, which is similar to session but will live until the next request.

Something like this:

public ActionResult DoSomething()
{
  TempData["partId"] = partId;
  TempData["catId"] = catId;
  TempData["catName"] = catName;
  return RedirectToAction("ProductSpecific");
}

public ActionResult ProductSpecific()
{
  var partId = TempData["partId"];
  var catId = TempData["catId"];
  var catName = TempData["catName"];

  var model = service.LoadProduct(partId, catId, catName);

  return View(model);
}

Update:

For a route:

 routes.MapRoute(
     name: "ProductRoute",
     url: "{controller}/{action}/{partId}/{categoryId}/{categoryname}",
     defults: new { controller = "product", action = "productspecific"}
 );

Add that route in the route.config class in app_start before your default routesm, and change your product specific method signature to accept the partid, catid and category name parameters. You can also use this from phil hack to profile your routes: Route Debugger

Upvotes: 1

Related Questions