destructi6n destructi6n - 3 months ago 10
C# Question

How to pass a string to my controller action

How can I map the following url...

domain.com/Products/product-name-here

I want to map this to my GetProduct action on my products controller.

Here is what I have in my route.config

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
name: "Product",
url: "product/{id}"
);

routes.MapRoute(
name: "EditProduct",
url:"Admin/Product/{action}",
defaults: new { controller = "Products", action = "Index"}
);

routes.MapRoute(
name:"ProductPages",
url:"Products/{id}",
defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional }
);

routes.MapRoute(
name:"OrderRoute",
url:"Orders/",
defaults: new { controller= "Order", action="Index"}
);
}


And here is my action that I want to map the route to.

[HttpGet]
public ActionResult GetProduct(string pageURL)
{

if ( string.IsNullOrWhiteSpace(pageURL))
return View("PageNotFound");


var product = db.Products.Where(x => x.PageURL == pageURL);

return View("GetProduct");

}

Answer

Add:

routes.MapRoute(
    name:"ProductPages",
    url:"Products/{pageURL}",
    defaults: new {controller = "Products", action = "GetProduct" }
);

Important: Your default route should be the last route in your route.config. In your code its the first one.

EDIT: your actual route "ProductPages" should be removed or edited to avoid conflict with my suggestion.