0

I have a list of products with some title field, e.g.:

ID   Title
1    TShirts CK
2    Brand new books
3    Selling whatever I have useless

Ok, I'm calling a Detail method this way:

<a href='@Url.Action("Detail", "Products", new { productId = 3 })'>See detail</a>

[Route("detail/{productId:int}")]
public ViewResult Detail(int productId) {
    //...
    return View();
}

The generated URL is:

http:example.com/products/detail/3

Well, the idea I want is show an URL like this:

http://example.com/products/detail/3/selling-wathever-i-have-useless

Is there a nice and clean way to do this, based on the given scenario?

abatishchev
  • 92,232
  • 78
  • 284
  • 421
Kiwanax
  • 1,197
  • 1
  • 20
  • 37

2 Answers2

0

I believe this has been termed a URL slug, which will make it 100x easier to search for. I suggest you start: https://stackoverflow.com/a/2921135/507025 for an algorithm to help you slugify your url.

If you have a database with the information, you might want to save the slugified description to it so you can check for duplicates upon the creation of a new item.

Routing will be very similar although you'll be needing to change your routing attribute to:

[Route("detail/{productName:string")]
public ViewResult Detail(string productName)
{
   return View();
}

You can then search your DB for the slugified description to return the item searched for OR use the terms given in a search to return multiple results.

There are probably different ways of doing this but now that you know it's called 'slug' you will have an easier time finding info about them.

Community
  • 1
  • 1
Josh
  • 537
  • 1
  • 7
  • 21
0

You can have a route as below and when you define Url.Action you can pass product title to some kind of method which convert the given text to URL friendly text.

Example

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

<a href='@Url.Action("Index", "Home", new { productId = product.ID, title = ToFriendlyUrl(product.Title) })'>See detail</a>

public ViewResult Detail(int productId, string title)
{
    // ...
    return View();
}

Thanks!

Saranga
  • 3,068
  • 1
  • 16
  • 26