Reputation: 5449
Hi I am trying to define a routing path for my URL.This is what it looks like so far:
routes.MapRoute(
name: "Category",
url: "{controller}/DisplayBooksByCategory/{categoryId}/{pageNumber}",
defaults: new { controller = "Home", action = "DisplayBooksByCategory" }
);
This works but it is not exactly what I want.At the moment my url looks something like this:
http://localhost:51208/Home/DisplayBooksByCategory/7/1
What I want is to be able to replace the categoryId with the actual category name.The category name is not passed as a parameter to the action only the categoryId.This is my action:
public ActionResult DisplayBooksByCategory(int pageNumber, int categoryId)
{
int bookByCategoryCount = bookRepository.CountBooksByCategory(categoryId);
var entities = new BooksAndCategories
{
Books = bookRepository.GetBookByCategory(categoryId, pageNumber, numberOfBooksOnPage),
PageNumber = pageNumber,
LastPageNumber = (bookByCategoryCount / numberOfBooksOnPage) + 1,
NumberOfBooksPerPage = numberOfBooksOnPage,
Categories = categoryRepository.GetCategories(),
CurentPage = "ProductManager",
CurentCategory = categoryId
};
return View("DisplayBooksByCategory", entities);
}
Is there any way to do that using the routing API without the need to modify the action?
Upvotes: 3
Views: 65
Reputation: 1038890
Where do you intend to get the category id from if you don't pass it in the request? That's not possible. The category id should stay as part of the url but you could include a friendly category name parameter in the route. But don't expect the id to automagically come from somewhere.
Just like StackOverflow does it for the questions. Look at your browser address bar. You should see something like this:
https://stackoverflow.com/questions/15290490/defining-routing-for-application
Notice the question id and a user friendly question title. This title is purely for displaying purposes and completely ignored. You could replace it with an arbitrary string if you want. The important part is what will uniquely identify the entity (which is the id).
Of course if your category names are unique you could use the category name instead of the id in the route. Also if you go that way, don't forget the fact that there are some special characters that are not allowed in the path portion of the url. Scott Hanselman wrote a nice blog post
on this topic. You will need to filter those dangerous characters out and replace the actual category name with a so called slug. Here's for example how StackOverflow does that: https://stackoverflow.com/a/25486/29407
Upvotes: 2