I have an index page which displays Categories (which have attributes: id and name) with the URL request: http://localhost:62745/home/index
.
When I click a category, I am taken to http://localhost:62745/Home/Products/6
.
I want to make the URL more detailed and replace the Category Id property 6
in the previous URL with the name
property of the Category which was just clicked.
My route config look like this:
public class RouteConfig
{
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: "Categories",
url: "{controller}/{action}/{categoryName}",
defaults: new { controller = "Category", action = "Index", categoryName = UrlParameter.Optional }
);
}
}
The first MapRoute()
method was already implemented. I added the second one hoping to solve my problem, but it didn't.
This is my controller action for products:
// GET: Product
public async Task<ActionResult> Index(int? id, string categoryName)
{
var products = (await db.Categories.Where(c => c.Id == id)
.SelectMany(p => p.Products.Select(x => new ProductViewModel { Id = x.Id, Name = x.Name, ByteImage = x.Image, Price = x.Price}))
.ToListAsync());
categoryName = db.Categories.Where(c => c.Id == id).Select(c => c.Name).ToString();
if (products == null)
{
return HttpNotFound();
}
return View(new ProductIndexViewModel{ Products = products, CategoryId = id });
}