Reputation: 1443
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");
}
Upvotes: 0
Views: 44
Reputation: 138
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.
Upvotes: 1
Reputation: 3030
This code doesn't actually call an action:
routes.MapRoute( name:"ProductPages", url:"Products/{id}", defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional } );
You want to add a route that uses actions like so (notice the action tag):
routes.MapRoute(
name:"ProductPages",
url:"Products/{action}/{id}",
defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional }
);
Upvotes: 0